Best Python code snippet using playwright-python
World.py
Source:World.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3"""4Created on Mon Jul 27 12:12:00 20205@author: andresmauriciotrianareina6"""7import numpy as np8import pandas as pd9import chart_studio.plotly as py10import plotly.graph_objs as go11import plotly.graph_objects as go12import cufflinks as cf13import seaborn as sns14import matplotlib.pyplot as plt15from matplotlib.pyplot import show16from pandas.plotting import register_matplotlib_converters17#%matplotlib inline18from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot19import plotly20import plotly.express as px21import time22from datetime import date, timedelta23from datetime import time24from datetime import datetime25import dash26import dash_core_components as dcc27import dash_html_components as html28from dash.dependencies import Input, Output29#####################################30#Data31df = pd.read_csv('https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv')32date_string = df['date']33#date_object = date_string.strptime('%Y,-%m')34#date_object = datetime.strptime(date_string, '%Y-%m')35df ['Year'] = df['date'].apply(lambda t: t.split('-')[0])36df ['Month'] = df['date'].apply(lambda t: t.split('-')[1])37df ['Year - Month'] = df ['Year'] + '-' + df ['Month']38#### Fecha39yesterday = date.today()-timedelta(days=1)40#yesterday = date.today()41fecha = yesterday.strftime("%Y-%m-%d")42#today = date.today()43#fecha = today.strftime("%Y-%m-%d")44otro = df['date'] == fecha45otro2 = df[otro]46with_world = otro2['location'] != 'World'47with_int1 = otro2[with_world]48with_int2 = with_int1['location'] != 'International'49actual = with_int1[with_int2]50### reemplazar valores nuos con 051#actual = actual.fillna(0)52df_order_total_cases = actual.sort_values('total_cases',ascending=False)53#df_order_total_cases.head()54df_order_total_death = actual.sort_values('total_deaths',ascending=False)55#df_order_total_death.head()56uno = (df['location'] != 'World') & (df['continent'] != 'International')57uno2 = df[uno]58uno3 = uno2['location'] != 'International'59uno4 = uno2[uno3]60sud = df['continent'] =='South America'61sudamerica = df[sud]62uno = (df['location'] != 'World') & (df['continent'] != 'International')63uno2 = df[uno]64uno3 = uno2['location'] != 'International'65uno4 = uno2[uno3]66uno5 = sudamerica['date'] == fecha67subamerica_hoy = sudamerica[uno5]68Wd = df['location'] == 'World'69World = df[Wd]70df_order_total_cases_per_mill = actual.sort_values('total_cases_per_million',ascending=False)71df_order_total_deaths_per_mill = actual.sort_values('total_deaths_per_million',ascending=False)72##### creación de graficas73def figures_to_html(figs, filename="20paisescontagios.html"):74    dashboard = open(filename, 'w')75    dashboard.write("<html><head></head><body>" + "\n")76    for fig in figs:77        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]78        dashboard.write(inner_html)79    dashboard.write("</body></html>" + "\n")80    81fig1 = px.bar(df_order_total_cases.head(20), x = 'location', y = 'total_cases', barmode='relative') 82   83figures_to_html([fig1])84def figures_to_html(figs, filename="20paisesmuertes.html"):85    dashboard = open(filename, 'w')86    dashboard.write("<html><head></head><body>" + "\n")87    for fig in figs:88        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]89        dashboard.write(inner_html)90    dashboard.write("</body></html>" + "\n")91    92fig1 = px.bar(df_order_total_death.head(20), x = 'location', y = 'total_deaths', barmode='relative')93figures_to_html([fig1])94def figures_to_html(figs, filename="Continente_contagios.html"):95    dashboard = open(filename, 'w')96    dashboard.write("<html><head></head><body>" + "\n")97    for fig in figs:98        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]99        dashboard.write(inner_html)100    dashboard.write("</body></html>" + "\n")101    102fig1 = px.pie(actual, values='total_cases', names='continent')103figures_to_html([fig1])104def figures_to_html(figs, filename="Continente_muertes.html"):105    dashboard = open(filename, 'w')106    dashboard.write("<html><head></head><body>" + "\n")107    for fig in figs:108        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]109        dashboard.write(inner_html)110    dashboard.write("</body></html>" + "\n")111    112fig1 = px.pie(actual, values='total_deaths', names='continent')113figures_to_html([fig1])114def figures_to_html(figs, filename="Contagiados_Fecha_Paises.html"):115    dashboard = open(filename, 'w')116    dashboard.write("<html><head></head><body>" + "\n")117    for fig in figs:118        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]119        dashboard.write(inner_html)120    dashboard.write("</body></html>" + "\n")121    122fig1 = px.line(df, x='date', y='total_cases', color='location')123figures_to_html([fig1])124def figures_to_html(figs, filename="fecha_Muertes_Paises.html"):125    dashboard = open(filename, 'w')126    dashboard.write("<html><head></head><body>" + "\n")127    for fig in figs:128        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]129        dashboard.write(inner_html)130    dashboard.write("</body></html>" + "\n")131    132fig1 = px.line(df, x='date', y='total_deaths', color='location')133figures_to_html([fig1])134def figures_to_html(figs, filename="Numero_contagios_fecha.html"):135    dashboard = open(filename, 'w')136    dashboard.write("<html><head></head><body>" + "\n")137    for fig in figs:138        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]139        dashboard.write(inner_html)140    dashboard.write("</body></html>" + "\n")141    142fig1 = px.line(World, x='date', y='total_cases')143figures_to_html([fig1])144def figures_to_html(figs, filename="Numero_muertes_fecha.html"):145    dashboard = open(filename, 'w')146    dashboard.write("<html><head></head><body>" + "\n")147    for fig in figs:148        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]149        dashboard.write(inner_html)150    dashboard.write("</body></html>" + "\n")151    152fig1 = px.line(World, x='date', y='total_deaths')153figures_to_html([fig1])154def figures_to_html(figs, filename="Mapa_Mundo_contagios.html"):155    dashboard = open(filename, 'w')156    dashboard.write("<html><head></head><body>" + "\n")157    for fig in figs:158        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]159        dashboard.write(inner_html)160    dashboard.write("</body></html>" + "\n")161    162data =  dict (type = 'choropleth',163             locations = actual['iso_code'],164             z = actual['total_cases'],165             text = actual['location'],166             colorbar = {'title': 'Contagiados'})167layout = dict (geo = dict (showframe = False, projection = {'type':'mercator'}))168choromap = go.Figure(data = [data], layout =layout) 169figures_to_html([choromap])170def figures_to_html(figs, filename="Mapa_Mundo_muertes.html"):171    dashboard = open(filename, 'w')172    dashboard.write("<html><head></head><body>" + "\n")173    for fig in figs:174        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]175        dashboard.write(inner_html)176    dashboard.write("</body></html>" + "\n")177    178data2 =  dict (type = 'choropleth',179             locations = actual['iso_code'],180             z = actual['total_deaths'],181             text = actual['location'],182             colorbar = {'title': 'Muertes'})183layout2 = dict (geo = dict (showframe = False, projection = {'type':'mercator'}))184choromap2 = go.Figure(data = [data2], layout =layout2)185figures_to_html([choromap2])186def figures_to_html(figs, filename="Tabla_contagiados_fallecidos.html"):187    dashboard = open(filename, 'w')188    dashboard.write("<html><head></head><body>" + "\n")189    for fig in figs:190        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]191        dashboard.write(inner_html)192    dashboard.write("</body></html>" + "\n")193    194    195#Today = date.today()196#fecha2 = Today.strftime("%Y-%m-%d")197yesterday = date.today()-timedelta(days=1)198fecha2 = yesterday.strftime("%Y-%m-%d")199otro = df['date'] == fecha2200otro2 = df[otro]201Only_world1 = otro2['location'] == 'World'202Only_world2 = otro2[Only_world1]203#Contagi = actual['total_cases'].sum()204Contagi = Only_world2['total_cases'].sum()205Total_deaths = Only_world2['total_deaths'].sum()206total_res_wor = pd.DataFrame({'Contagiados': [Contagi],'Fallecidos': [Total_deaths], 'Fecha':[fecha2]})207fig1 = go.Figure(data=[go.Table(208    header=dict(values=list(total_res_wor.columns),209                fill_color='rgba(15, 78, 64, 0.1)',210                align='center'),211    cells=dict(values=[total_res_wor.Contagiados, total_res_wor.Fallecidos, total_res_wor.Fecha ],212               fill_color='rgba(255, 255, 255, 0.1)',213               align='center',214               format = [",.0f", ",.0f",None]))215])216figures_to_html([fig1])217yesterday = date.today()-timedelta(days=1)218#yesterday = date.today()219fecha = yesterday.strftime("%Y-%m-%d")220otro = df['date'] == fecha221otro2 = df[otro]222with_world = otro2['location'] != 'World'223with_int1 = otro2[with_world]224with_int2 = with_int1['location'] != 'International'225actual = with_int1[with_int2]226def figures_to_html(figs, filename="Cases_per_millon.html"):227    dashboard = open(filename, 'w')228    dashboard.write("<html><head></head><body>" + "\n")229    for fig in figs:230        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]231        dashboard.write(inner_html)232    dashboard.write("</body></html>" + "\n")233    234    235fig1 = px.bar(df_order_total_cases_per_mill.head(20), x = 'location', y = 'total_cases_per_million')236figures_to_html([fig1])237def figures_to_html(figs, filename="deaths_per_millon.html"):238    dashboard = open(filename, 'w')239    dashboard.write("<html><head></head><body>" + "\n")240    for fig in figs:241        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]242        dashboard.write(inner_html)243    dashboard.write("</body></html>" + "\n")244    245    246fig1 = px.bar(df_order_total_deaths_per_mill.head(20), x = 'location', y = 'total_deaths_per_million')247figures_to_html([fig1])248def figures_to_html(figs, filename="deaths_extreme_poverty.html"):249    dashboard = open(filename, 'w')250    dashboard.write("<html><head></head><body>" + "\n")251    for fig in figs:252        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]253        dashboard.write(inner_html)254    dashboard.write("</body></html>" + "\n")255    256    257#fig1 = px.scatter(actual, x="extreme_poverty", y="total_deaths", color = "continent")258#figures_to_html([fig1])259def figures_to_html(figs, filename="cardiovasc_death_rate.html"):260    dashboard = open(filename, 'w')261    dashboard.write("<html><head></head><body>" + "\n")262    for fig in figs:263        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]264        dashboard.write(inner_html)265    dashboard.write("</body></html>" + "\n")266    267    268#fig1 = px.scatter(actual, x="cardiovasc_death_rate", y="total_deaths", color = "continent")269#figures_to_html([fig1])270def figures_to_html(figs, filename="diabetes_prevalence.html"):271    dashboard = open(filename, 'w')272    dashboard.write("<html><head></head><body>" + "\n")273    for fig in figs:274        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]275        dashboard.write(inner_html)276    dashboard.write("</body></html>" + "\n")277    278    279#fig1 = px.scatter(actual, x="diabetes_prevalence", y="total_deaths", color = "continent")280#figures_to_html([fig1])281def figures_to_html(figs, filename="New_cases_per_millon.html"):282    dashboard = open(filename, 'w')283    dashboard.write("<html><head></head><body>" + "\n")284    for fig in figs:285        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]286        dashboard.write(inner_html)287    dashboard.write("</body></html>" + "\n")288    289    290df_order_new_cases_per_mill = actual.sort_values('new_cases_per_million',ascending=False)291fig1 = px.bar(df_order_new_cases_per_mill.head(20), x = 'location', y = 'new_cases_per_million')292figures_to_html([fig1])293def figures_to_html(figs, filename="New_deaths_per_millon.html"):294    dashboard = open(filename, 'w')295    dashboard.write("<html><head></head><body>" + "\n")296    for fig in figs:297        inner_html = fig.to_html().split('<body>')[1].split('</body>')[0]298        dashboard.write(inner_html)299    dashboard.write("</body></html>" + "\n")300    301    302df_order_new_deaths_per_mill = actual.sort_values('new_deaths_per_million',ascending=False)303fig1 = px.bar(df_order_new_deaths_per_mill.head(20), x = 'location', y = 'new_deaths_per_million')...builders.py
Source:builders.py  
...9import components.stocks as stocks10import components.monitor as monitor11import components.logging as logging12from configuration import config13def build_header_now_playing_column_inner_html():14    template = '''15    <div id="now-playing-metadata" data-track-uri="{track_uri}" data-playlist-uri="{playlist_uri}">16        <div id="now-playing-playlist">{playlist_name}</div>17        <div id="now-playing-song">{track_name}</div>18    </div>19    <div id="now-playing-image-container">20        <div id="now-playing-image-overlay" onclick="spotifyPlaylistRemoveButtonClicked()">21            <img id="now-playing-image" data-destination="{destination}" src="/spotify/now_playing.jpeg" />22        </div>23    </div>24    '''25    tn, turi, pn, puri = None, None, None, None #spotify.now_playing_info()26    if tn == None:27        tn = '-'...WebScrapingPartida.py
Source:WebScrapingPartida.py  
...28    VermelhoQuatro = page.query_selector("#__next > div.css-1n276kj.eafu1dm0 > div.css-yspf3p.e1k2e1zv5 > table.css-18rus4b.e1snzzz71 > tbody > tr:nth-child(4) > td.summoner-name > a")29    VermelhoQuatroElo = page.query_selector("#__next > div.css-1n276kj.eafu1dm0 > div.css-yspf3p.e1k2e1zv5 > table.css-18rus4b.e1snzzz71 > tbody > tr:nth-child(4) > td.current-rank > div")30    VermelhoCinco = page.query_selector("#__next > div.css-1n276kj.eafu1dm0 > div.css-yspf3p.e1k2e1zv5 > table.css-18rus4b.e1snzzz71 > tbody > tr:nth-child(5) > td.summoner-name > a")31    VermelhoCincoElo = page.query_selector("#__next > div.css-1n276kj.eafu1dm0 > div.css-yspf3p.e1k2e1zv5 > table.css-18rus4b.e1snzzz71 > tbody > tr:nth-child(5) > td.current-rank > div")32    AzulUm_ = (AzulUm.inner_html()); AzulUmElo_ = (AzulUmElo.inner_html())33    AzulDois_ = (AzulDois.inner_html()); AzulDoisElo_ = (AzulDoisElo.inner_html())34    AzulTres_ = (AzulTres.inner_html()); AzulTresElo_ = (AzulTresElo.inner_html())35    AzulQuatro_ = (AzulQuatro.inner_html()); AzulQuatroElo_ = (AzulQuatroElo.inner_html())36    AzulCinco_ = (AzulCinco.inner_html()); AzulCincoElo_ = (AzulCincoElo.inner_html())37    VermelhoUm_ = (VermelhoUm.inner_html()); VermelhoUmElo_ = (VermelhoUmElo.inner_html())38    VermelhoDois_ = (VermelhoDois.inner_html()); VermelhoDoisElo_ = (VermelhoDoisElo.inner_html())39    VermelhoTres_ = (VermelhoTres.inner_html()); VermelhoTresElo_ = (VermelhoTresElo.inner_html())40    VermelhoQuatro_ = (VermelhoQuatro.inner_html()); VermelhoQuatroElo_ = (VermelhoQuatroElo.inner_html())41    VermelhoCinco_ = (VermelhoCinco.inner_html()); VermelhoCincoElo_ = (VermelhoCincoElo.inner_html())42    times = (f'Time Azul: \n \n {AzulUm_} - {AzulUmElo_} \n {AzulDois_} - {AzulDoisElo_}\n {AzulTres_} - {AzulTresElo_}\n {AzulQuatro_} - {AzulQuatroElo_}\n {AzulCinco_} - {AzulCincoElo_}\n\n Time Vermelho: \n \n {VermelhoUm_} - {VermelhoUmElo_} \n {VermelhoDois_} - {VermelhoDoisElo_} \n {VermelhoTres_} - {VermelhoTresElo_} \n {VermelhoQuatro_} - {VermelhoQuatroElo_} \n {VermelhoCinco_} - {VermelhoCincoElo_}')43    page.locator("div.css-yspf3p.e1k2e1zv5").screenshot(path="Game\WebScrapingPartida\AOVIVOPartida.png")...details.py
Source:details.py  
1from helper import inner_html, remove_tags2def hourly_forecast(soup):3    temp_map = {}4    for i in range(1, 6):5        time = inner_html(soup.select(6            f'.HourlyWeatherCard--TableWrapper--2kboH > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > h3:nth-child(1) > span:nth-child(1)'))7        temp = inner_html(soup.select(8            f'.HourlyWeatherCard--TableWrapper--2kboH > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > div:nth-child(2) > span:nth-child(1)'))9        precipitation = remove_tags(str(soup.select(10            f'.HourlyWeatherCard--TableWrapper--2kboH > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > div:nth-child(4)')[11                                            0]))12        temp_map[i] = {13            "time": time,14            "highest_temp": temp,15            "precipitation": precipitation16        }17    return temp_map18def daily_forecast(soup):19    temp_map = {}20    for i in range(1, 6):21        time = inner_html(soup.select(22            f".DailyWeatherCard--TableWrapper--12r1N > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > "23            f"h3:nth-child(1) > span:nth-child(1)"))24        highest_temp = inner_html(soup.select(25            f".DailyWeatherCard--TableWrapper--12r1N > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > "26            f"div:nth-child(2) > span:nth-child(1)"))27        lowest_temp = inner_html(soup.select(28            f".DailyWeatherCard--TableWrapper--12r1N > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > "29            f"div:nth-child(3) > span:nth-child(1)"))30        precipitation = remove_tags(str(soup.select(31            f".DailyWeatherCard--TableWrapper--12r1N > ul:nth-child(1) > li:nth-child({i}) > a:nth-child(1) > "32            f"div:nth-child(5)")[0]))33        temp_map[i] = {34            "time": time,35            "highest_temp": highest_temp,36            "lowest_temp": lowest_temp,37            "precipitation": precipitation38        }39    return temp_map40def today_forecast(soup):41    time = ["morning", "afternoon", "evening", "night"]42    temp_map = {}43    i = 144    for t in time:45        precip_selector = f'.WeatherTable--wide--YogM9 > li:nth-child({i}) > a:nth-child(1) > div:nth-child(4)'46        try:47            temp_map[t] = {48                "temperature": inner_html(soup.select(49                    f'.WeatherTable--wide--YogM9 > li:nth-child({i}) > a:nth-child(1) > div:nth-child(2) > '50                    f'span:nth-child(1)')),51                "precipitation": remove_tags(str(soup.select(precip_selector)[0])),52            }53        except IndexError:54            precip_selector = f'li.Column--active--FeXwd:nth-child({i}) > a:nth-child(1) > div:nth-child(4)'55            temp_map[t] = {56                "temperature": inner_html(soup.select(57                    f'.WeatherTable--wide--YogM9 > li:nth-child({i}) > a:nth-child(1) > div:nth-child(2) > '58                    f'span:nth-child(1)')),59                "precipitation": remove_tags(str(soup.select(precip_selector)[0]))60            }61        finally:62            i += 163    return temp_map64def today_weather_details(soup):65    weather_type = inner_html(soup.select('.CurrentConditions--phraseValue--2xXSr'))66    avg_temperature = inner_html(soup.select('.TodayDetailsCard--feelsLikeTempValue--2aogo'))67    today_max_temp = inner_html(68        soup.select('div.ListItem--listItem--1r7mf:nth-child(1) > div:nth-child(3) > span:nth-child(1)'))69    today_min_temp = inner_html(70        soup.select('div.ListItem--listItem--1r7mf:nth-child(1) > div:nth-child(3) > span:nth-child(2)'))71    wind_speed = remove_tags(inner_html(soup.select('.Wind--windWrapper--1Va1P')))72    humidity = inner_html(73        soup.select('div.ListItem--listItem--1r7mf:nth-child(3) > div:nth-child(3) > span:nth-child(1)'))74    pressure = remove_tags(inner_html(soup.select('.Pressure--pressureWrapper--3olKd')))75    uv_index = inner_html(76        soup.select('div.ListItem--listItem--1r7mf:nth-child(6) > div:nth-child(3) > span:nth-child(1)'))77    visibility = inner_html(78        soup.select('div.ListItem--listItem--1r7mf:nth-child(7) > div:nth-child(3) > span:nth-child(1)'))79    moon_phase = inner_html(soup.select('div.ListItem--listItem--1r7mf:nth-child(8) > div:nth-child(3)'))80    temp_map = {81        "weather_type": weather_type,82        "avg_temperature": avg_temperature,83        "today_max_temp": today_max_temp,84        "today_min_temp": today_min_temp,85        "wind_speed": wind_speed,86        "humidity": humidity,87        "pressure": pressure,88        "uv_index": uv_index,89        "visibility": visibility,90        "moon_phase": moon_phase,91    }...LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
