范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文
国学影视

自动化无痕浏览器对比测试,PlayWrightVsSelenium,基于Python3。10

  也许每一个男子全都有过这样的两个女人,至少两个。娶了红玫瑰,久而久之,红的变了墙上的一抹蚊子血,白的还是床前明月光;娶了白玫瑰,白的便是衣服上沾的一粒饭黏子,红的却是心口上一颗朱砂痣。--张爱玲《红玫瑰与白玫瑰》
  Selenium一直都是Python开源自动化浏览器工具的王者,但这两年微软开源的PlayWright异军突起,后来者居上,隐隐然有撼动Selenium江湖地位之势,本次我们来对比PlayWright与Selenium之间的差异,看看曾经的玫瑰花Selenium是否会变成蚊子血。 PlayWright的安装和使用
  PlayWright是由业界大佬微软(Microsoft)开源的端到端 Web 测试和自动化库,可谓是大厂背书,功能满格,虽然作为无头浏览器,该框架的主要作用是测试 Web 应用,但事实上,无头浏览器更多的是用于 Web 抓取目的,也就是爬虫。
  首先终端运行安装命令: pip3 install playwright
  程序返回: Successfully built greenlet Installing collected packages: pyee, greenlet, playwright   Attempting uninstall: greenlet     Found existing installation: greenlet 2.0.2     Uninstalling greenlet-2.0.2:       Successfully uninstalled greenlet-2.0.2 Successfully installed greenlet-2.0.1 playwright-1.30.0 pyee-9.0.4
  目前最新稳定版为1.30.0
  随后可以选择直接安装浏览器驱动: playwright install
  程序返回: Downloading Chromium 110.0.5481.38 (playwright build v1045) from https://playwright.azureedge.net/builds/chromium/1045/chromium-mac-arm64.zip 123.8 Mb [====================] 100% 0.0s Chromium 110.0.5481.38 (playwright build v1045) downloaded to /Users/liuyue/Library/Caches/ms-playwright/chromium-1045 Downloading FFMPEG playwright build v1008 from https://playwright.azureedge.net/builds/ffmpeg/1008/ffmpeg-mac-arm64.zip 1 Mb [====================] 100% 0.0s FFMPEG playwright build v1008 downloaded to /Users/liuyue/Library/Caches/ms-playwright/ffmpeg-1008 Downloading Firefox 108.0.2 (playwright build v1372) from https://playwright.azureedge.net/builds/firefox/1372/firefox-mac-11-arm64.zip 69.8 Mb [====================] 100% 0.0s Firefox 108.0.2 (playwright build v1372) downloaded to /Users/liuyue/Library/Caches/ms-playwright/firefox-1372 Downloading Webkit 16.4 (playwright build v1767) from https://playwright.azureedge.net/builds/webkit/1767/webkit-mac-12-arm64.zip 56.9 Mb [====================] 100% 0.0s Webkit 16.4 (playwright build v1767) downloaded to /Users/liuyue/Library/Caches/ms-playwright/webkit-1767
  默认会下载Chromium内核、Firefox以及Webkit驱动。
  其中使用最广泛的就是基于Chromium内核的浏览器,最负盛名的就是Google的Chrome和微软自家的Edge。
  确保当前电脑安装了Edge浏览器,让我们小试牛刀一把: from playwright.sync_api import sync_playwright import time with sync_playwright() as p:     browser = p.chromium.launch(channel="msedge", headless=True)     page = browser.new_page()     page.goto("http:/v3u.cn")     page.screenshot(path=f"./example-v3u.png")     time.sleep(5)     browser.close()
  这里导入sync_playwright模块,顾名思义,同步执行,通过上下文管理器开启浏览器进程。
  随后通过channel指定edge浏览器,截图后关闭浏览器进程:
  我们也可以指定headless参数为True,让浏览器再后台运行: from playwright.sync_api import sync_playwright with sync_playwright() as p:     browser = p.chromium.launch(channel="msedge", headless=True)     page = browser.new_page()     page.goto("http:/v3u.cn")     page.screenshot(path=f"./example-v3u.png")     browser.close()
  除了同步模式,PlayWright也支持异步非阻塞模式: import asyncio from playwright.async_api import async_playwright  async def main():     async with async_playwright() as p:         browser = await p.chromium.launch(channel="msedge", headless=False)         page = await browser.new_page()         await page.goto("http://v3u.cn")         print(await page.title())         await browser.close()  asyncio.run(main())
  可以通过原生协程库asyncio进行调用,PlayWright内置函数只需要添加await关键字即可,非常方便,与之相比,Selenium原生库并不支持异步模式,必须安装三方扩展才可以。
  最炫酷的是,PlayWright可以对用户的浏览器操作进行录制,并且可以转换为相应的代码,在终端执行以下命令: python -m playwright codegen --target python -o "edge.py" -b chromium --channel=msedge
  这里通过codegen命令进行录制,指定浏览器为edge,将所有操作写入edge.py的文件中:
  与此同时,PlayWright也支持移动端的浏览器模拟,比如苹果手机: from playwright.sync_api import sync_playwright with sync_playwright() as p:     iphone_13 = p.devices["iPhone 13 Pro"]     browser = p.webkit.launch(headless=False)     page = browser.new_page()     page.goto("https://v3u.cn")     page.screenshot(path="./v3u-iphone.png")     browser.close()
  这里模拟Iphone13pro的浏览器访问情况。
  当然了,除了UI功能测试,我们当然还需要PlayWright帮我们干点脏活累活,那就是爬虫: from playwright.sync_api import sync_playwright    def extract_data(entry):  	name = entry.locator("h3").inner_text().strip(" ").strip()  	capital = entry.locator("span.country-capital").inner_text()  	population = entry.locator("span.country-population").inner_text()  	area = entry.locator("span.country-area").inner_text()    	return {"name": name, "capital": capital, "population": population, "area (km sq)": area}    with sync_playwright() as p:  	# launch the browser instance and define a new context  	browser = p.chromium.launch()  	context = browser.new_context()  	# open a new tab and go to the website  	page = context.new_page()  	page.goto("https://www.scrapethissite.com/pages/simple/")  	page.wait_for_load_state("load")  	# get the countries  	countries = page.locator("p.country")  	n_countries = countries.count()    	# loop through the elements and scrape the data  	data = []    	for i in range(n_countries):  		entry = countries.nth(i)  		sample = extract_data(entry)  		data.append(sample)    browser.close()
  这里data变量就是抓取的数据内容: [  	{"name": "Andorra", "capital": "Andorra la Vella", "population": "84000", "area (km sq)": "468.0"},  	{"name": "United Arab Emirates", "capital": "Abu Dhabi", "population": "4975593", "area (km sq)": "82880.0"},  	{"name": "Afghanistan", "capital": "Kabul", "population": "29121286", "area (km sq)": "647500.0"},  	{"name": "Antigua and Barbuda", "capital": "St. John"s", "population": "86754", "area (km sq)": "443.0"},  	{"name": "Anguilla", "capital": "The Valley", "population": "13254", "area (km sq)": "102.0"},  	...  ]
  基本上,该有的功能基本都有,更多功能请参见官方文档:https://playwright.dev/python/docs/library Selenium
  Selenium曾经是用于网络抓取和网络自动化的最流行的开源无头浏览器工具之一。在使用 Selenium 进行抓取时,我们可以自动化浏览器、与 UI 元素交互并在 Web 应用程序上模仿用户操作。Selenium 的一些核心组件包括 WebDriver、Selenium IDE 和 Selenium Grid。
  关于Selenium的一些基本操作请移玉步至:python3.7爬虫:使用Selenium带Cookie登录并且模拟进行表单上传文件,这里不作过多赘述。
  如同前文提到的,与Playwright相比,Selenium需要第三方库来实现异步并发执行,同时,如果需要录制动作视频,也需要使用外部的解决方案。
  就像Playwright那样,让我们使用 Selenium 构建一个简单的爬虫脚本。
  首先导入必要的模块并配置 Selenium 实例,并且通过设置确保无头模式处于活动状态option.headless = True: from selenium import webdriver  from selenium.webdriver.chrome.service import Service  from selenium.webdriver.common.by import By  # web driver manager: https://github.com/SergeyPirogov/webdriver_manager  # will help us automatically download the web driver binaries  # then we can use `Service` to manage the web driver"s state.  from webdriver_manager.chrome import ChromeDriverManager    def extract_data(row):  	name = row.find_element(By.TAG_NAME, "h3").text.strip(" ").strip()  	capital = row.find_element(By.CSS_SELECTOR, "span.country-capital").text  	population = row.find_element(By.CSS_SELECTOR, "span.country-population").text  	area = row.find_element(By.CSS_SELECTOR, "span.country-area").text    	return {"name": name, "capital": capital, "population": population, "area (km sq)": area}    options = webdriver.ChromeOptions()  options.headless = True  # this returns the path web driver downloaded  chrome_path = ChromeDriverManager().install()  # define the chrome service and pass it to the driver instance  chrome_service = Service(chrome_path)  driver = webdriver.Chrome(service=chrome_service, options=options)    url = "https://www.scrapethissite.com/pages/simple"    driver.get(url)  # get the data ps  countries = driver.find_elements(By.CSS_SELECTOR, "p.country")    # extract the data  data = list(map(extract_data, countries))    driver.quit()
  数据返回: [  	{"name": "Andorra", "capital": "Andorra la Vella", "population": "84000", "area (km sq)": "468.0"},  	{"name": "United Arab Emirates", "capital": "Abu Dhabi", "population": "4975593", "area (km sq)": "82880.0"},  	{"name": "Afghanistan", "capital": "Kabul", "population": "29121286", "area (km sq)": "647500.0"},  	{"name": "Antigua and Barbuda", "capital": "St. John"s", "population": "86754", "area (km sq)": "443.0"},  	{"name": "Anguilla", "capital": "The Valley", "population": "13254", "area (km sq)": "102.0"},  	...  ]性能测试
  在数据抓取量一样的前提下,我们当然需要知道到底谁的性能更好,是PlayWright,还是Selenium?
  这里我们使用Python3.10内置的time模块来统计爬虫脚本的执行速度。
  PlayWright: import time  from playwright.sync_api import sync_playwright    def extract_data(entry):  	name = entry.locator("h3").inner_text().strip(" ").strip()  	capital = entry.locator("span.country-capital").inner_text()  	population = entry.locator("span.country-population").inner_text()  	area = entry.locator("span.country-area").inner_text()    	return {"name": name, "capital": capital, "population": population, "area (km sq)": area}    start = time.time()  with sync_playwright() as p:  	# launch the browser instance and define a new context  	browser = p.chromium.launch()  	context = browser.new_context()  	# open a new tab and go to the website  	page = context.new_page()  	page.goto("https://www.scrapethissite.com/pages/")  	# click to the first page and wait while page loads  	page.locator("a[href="/pages/simple/"]").click()  	page.wait_for_load_state("load")  	# get the countries  	countries = page.locator("p.country")  	n_countries = countries.count()    	data = []    	for i in range(n_countries):  		entry = countries.nth(i)  		sample = extract_data(entry)  		data.append(sample)    browser.close()  end = time.time()    print(f"The whole script took: {end-start:.4f}")
  Selenium: import time  from selenium import webdriver  from selenium.webdriver.chrome.service import Service  from selenium.webdriver.common.by import By  # web driver manager: https://github.com/SergeyPirogov/webdriver_manager  # will help us automatically download the web driver binaries  # then we can use `Service` to manage the web driver"s state.  from webdriver_manager.chrome import ChromeDriverManager    def extract_data(row):  	name = row.find_element(By.TAG_NAME, "h3").text.strip(" ").strip()  	capital = row.find_element(By.CSS_SELECTOR, "span.country-capital").text  	population = row.find_element(By.CSS_SELECTOR, "span.country-population").text  	area = row.find_element(By.CSS_SELECTOR, "span.country-area").text    	return {"name": name, "capital": capital, "population": population, "area (km sq)": area}    # start the timer  start = time.time()    options = webdriver.ChromeOptions()  options.headless = True  # this returns the path web driver downloaded  chrome_path = ChromeDriverManager().install()  # define the chrome service and pass it to the driver instance  chrome_service = Service(chrome_path)  driver = webdriver.Chrome(service=chrome_service, options=options)    url = "https://www.scrapethissite.com/pages/"    driver.get(url)  # get the first page and click to the link  first_page = driver.find_element(By.CSS_SELECTOR, "h3.page-title a")  first_page.click()  # get the data p and extract the data using beautifulsoup  countries_container = driver.find_element(By.CSS_SELECTOR, "section#countries p.container")  countries = driver.find_elements(By.CSS_SELECTOR, "p.country")    # scrape the data using extract_data function  data = list(map(extract_data, countries))    end = time.time()    print(f"The whole script took: {end-start:.4f}")    driver.quit()
  测试结果:
  Y轴是执行时间,一望而知,Selenium比PlayWright差了大概五倍左右。 红玫瑰还是白玫瑰?
  不得不承认,Playwright 和 Selenium 都是出色的自动化无头浏览器工具,都可以完成爬虫任务。我们还不能断定那个更好一点,所以选择那个取决于你的网络抓取需求、你想要抓取的数据类型、浏览器支持和其他考虑因素:
  Playwright 不支持真实设备,而 Selenium 可用于真实设备和远程服务器。
  Playwright 具有内置的异步并发支持,而 Selenium 需要第三方工具。
  Playwright 的性能比 Selenium 高。
  Selenium 不支持详细报告和视频录制等功能,而 Playwright 具有内置支持。
  Selenium 比 Playwright 支持更多的浏览器。
  Selenium 支持更多的编程语言。 结语
  如果您看完了本篇文章,那么到底谁是最好的无头浏览器工具,答案早已在心间,所谓强中强而立强,只有弱者才害怕竞争,相信PlayWright的出现会让Selenium变为更好的自己,再接再厉,再创辉煌。

这位日本家长分享了培养孩子读书的方法超受欢迎作者阳光家长学院XD老师关注更多精彩内容一位日本家长在网上分享培养孩子读书的方法,受到网友的热烈回响,不少父母看到这个方法之后两眼放光,表示今晚就要去尝试!这位家长在社交平台上分享新都区妇幼保健院这项人间值得的技术,准妈妈一定要了解一直以来,生孩子对于女性来说都是一场痛苦又幸福的经历。很多时候,在面对分娩时,击垮产妇的往往不是产程的长短,而是令人绝望的产痛。生孩子到底有多痛?临床上通常按照010分进行疼痛程度孩子出生家长们就开始内卷,一定要用对方法,孩子才会活泼开朗对于宝爸宝妈们来说,宝宝健康快乐无忧无虑地成长,就是父母一生最大的心愿。然而随着时代的进步,各种各样的词语出现在宝宝成长的道路上,当下最出名的应该是内卷。内卷是近两年新出现的各行各煮熟的鸭子!辽宁男篮一主力缺席训练,来看看杨鸣的G2赛前采访北京时间4月22日,CBA联赛总决赛G2即将打响。其实,对于辽宁男篮而言,总冠军就是煮熟的鸭子,这次没人可以再将其打飞。辽宁男篮在结束G1之后,全员表现得非常放松,比赛确实没有什么勇士三巨头再现!系列赛打成30,MVP将要回家?北京时间4月22日报道,NBA季后赛掘金主场迎接勇士的挑战。掘金已经在勇士的主场被连续吊打两场比赛了,约老师作为mvp脸都快挂不住了,回到主场他们能否绝地翻盘?下面来看看本场比赛的30胜掘金!勇士三后卫80分,勇士拿到赛点,约基奇空砍37185北京时间4月22日,NBA季后赛继续进行,勇士队前往客场挑战掘金队,已经20领先的勇士队,如果此役赢下G3,那么他们就将30领先对手,球队优势将会非常明显,晋级下一轮的概率将会很大世锦赛第六日16强最后2席确定!次轮赵心童落后,马叔巨大领先2022斯诺克世锦赛精彩继续!第六日的比赛产生了最后2个16强席位,分别为特鲁姆普和桑坎姆。另外还有2场第二轮第一阶段的比赛。赵心童暂35落后,马叔71巨大优势领先。正赛首轮最后两为何说湖人队史阵容是历史最强?看了这5人的名字你就懂NBA历史上的强队真不少,有乔丹的公牛,拉塞尔的绿凯,邓肯的马刺,科比的湖人。不过要说队史最强阵容,还得是看湖人队。湖人队真的是太富裕了,太多历史顶级球星都在这效力过。如果湖人组一探球直播曼城收购哈兰德!C罗惨遭丧子之痛一曼城准备触发7500万欧元解约条款收购多特前锋哈兰德去年哈里凯恩发出渴望离队的信号后,曼城犹豫再三后放弃凯恩,使得球队依然没有中锋支点,比赛得分也是显得艰难。幸好的是,凯恩也显得官宣!国羽公布汤尤杯名单,三位奥运冠军缺席,女队派出最强阵容2022年4月22日,国羽官宣,公布汤尤杯名单,教练组派出以年轻选手为主的阵容,三位奥运冠军谌龙张楠王懿律缺席,另外石宇奇郑思维黄雅琼也不参加,女队派出最强阵容,陈雨菲领衔,另外男东部决赛大乱猜先定个基调,不出意外,个人倾向于东部决赛会是马赛克76人队vs芝加哥公牛队!一理性层面1。目前76人已经30削弱版的猛龙,除非里弗斯继续创造历史,继13被逆转以后,成为nba历史上
全球超级计算机Top500榜单发布,Frontier凭借最快速度稳居榜首近日,世界最强大超级计算机TOP500名单在全球超级计算机大会上发布。FrontierFugaku和LUMI计算机位列前三。图排名第一的Frontier计算机(来源资料图)榜单中的吉利全新微型电动车实车曝光,或定名几何熊猫mini,可爱风格设计日前,我们从最新一期工信部申报目录中获悉,吉利推出了一款全新微型电动车型,从车尾的标识来看,这款车很有可能会被命名为熊猫mini,印象中该车曾在几何品牌下进行申报,此次则对该车的品一文带你速览BinanceLabs近期孵化计划入选项目BinanceLabs全球孵化计划已正式启动,超过500个项目提出申请,分布在了Web3基础设施工具GameFiMetaverseDeFi等赛道。近日,BinanceLabs全球孵6000mAh大电池手机被下放到1199元,vivo是在做什么?千元机的极限配置是什么?可能这个问题不能有绝对性的答案!因为时代在进步,科技也在进步,手机厂商们在手机技术上越来越好,肯定就会有越来越多优秀的配置下放给千元机,让普通用户也能享受到最火后台管理系统RuoYi项目探秘,之三上篇中,我们初步探究了RuoYi项目是如何进行登录信息传输验证码校验密码校验,以及密码存储安全性方案。我们了解到,整个的验证实现是围绕Shiro框架进行的,而数据的传输安全性,Ru凯迪拉克被曝放宽新能源车销售渠道,首款纯电10月销量722辆凯迪拉克在调整其新能源车型的销售模式。据财经汽车报道,凯迪拉克在10月底调整了新能源汽车销售渠道政策,此前只向部分经销商开放新能源业务的纯电IQ专区,现已向所有凯迪拉克经销商开放。拉美最大太阳能项目之一塞拉多骄阳启动运营由中国企业提供光伏组件中新社北京11月18日电(记者庞无忌)记者18日从巴西矿业巨头淡水河谷提供的消息获知当地时间17日,淡水河谷在巴西米纳斯吉拉斯州北部的雅伊巴市启动了塞拉多骄阳(SoldoCerra孕妈妈产前必检项目曝光,不必检的就不要浪费,我们只检必要的孕妇怀孕之后,需要面临去医院产检的问题,但有些孕妇却不太愿意去医院。疫情当前,医院其实并不太安全,而且医院里面生病的人很多,这对孕妇来说有一定隐患。有一部分孕妇就直接不去医院产检了广州淘宝第一村210亿元旧改项目方案获批,越秀地产为合作方广州淘宝第一村更新后的改造实施方案日前已获广州市住建局批复。11月12日,广州市番禺区南村镇里仁洞村旧改咨询官方微信号披露消息称,里仁洞村更新改造实施方案已获广州市住建局批复。航拍钠离子电池材料行业研究产业化指日可待,钠电未来可期(报告出品方光大证券)1宁德时代加码布局,钠电有望加速发展1。1宁德时代加码布局,钠离子电池产业化可期钠离子电池是一种摇椅式二次电池,其工作原理与锂离子电池类似,均利用离子在电极之金融16条,不但是政策性利好,更加是信心的转向房地产救市一年多,未见显著成效。为什么?最大的原因在于市场信心没有得到有效恢复。为什么市场信心没有恢复?在于政策存在一定的模糊性,导致在执行层面有顾虑,怕担责,投鼠忌器。比如从6月