也许每一个男子全都有过这样的两个女人,至少两个。娶了红玫瑰,久而久之,红的变了墙上的一抹蚊子血,白的还是床前明月光;娶了白玫瑰,白的便是衣服上沾的一粒饭黏子,红的却是心口上一颗朱砂痣。--张爱玲《红玫瑰与白玫瑰》

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("\n").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("div.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("\n").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 divs
countries = driver.find_elements(By.CSS_SELECTOR, "div.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("\n").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("div.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("\n").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 div and extract the data using beautifulsoup
countries_container = driver.find_element(By.CSS_SELECTOR, "section#countries div.container")
countries = driver.find_elements(By.CSS_SELECTOR, "div.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变为更好的自己,再接再厉,再创辉煌。

玫瑰花变蚊子血,自动化无痕浏览器对比测试,新贵PlayWright Vs 老牌Selenium,基于Python3.10的更多相关文章

  1. Python+Selenium自动化-设置浏览器大小、刷新页面、前进和后退

    Python+Selenium自动化-设置浏览器大小.刷新页面.前进和后退   1.设置浏览器大小 maximize_window():设置浏览器大小为全屏 set_window_size(500,5 ...

  2. Selenium_python自动化跨浏览器执行测试

    Selenium_python自动化跨浏览器执行测试(简单多线程案例)  转:https://www.cnblogs.com/dong-c/p/8976746.html 跨浏览器测试是功能测试的一个分 ...

  3. RobotFramework自动化测试框架-Selenium Web自动化(三)关于在RobotFramework中如何使用Selenium很全的总结(下)

    本文紧接着RobotFramework自动化测试框架-Selenium Web自动化(二)关于在RobotFramework中如何使用Selenium很全的总结(上)继续分享RobotFramewor ...

  4. 基于Python3.7 Robot Framework自动化框架搭建

    一.Robot Framework 和 Selenium 的区别(面试常问) 主流自动化测试框架有Robot Framework 和 Selenium,请根据实际场景选用不同的框架,以下总结各自优缺点 ...

  5. 在浏览器上开发GO和Vue!(基于code-server)

    在浏览器上开发GO和Vue!(基于code-server) 曾几何时,开发者们都被安装编程环境苦恼,尽管现在很多语言的开发环境已经不难装了,但是如果我们能有一个运行在云端的编译器,那么我们就可以随时随 ...

  6. Selenium自动化Chrome浏览器 在windows下窗口最大化

    本人由于是搞自动化时间不长,所以踩了很多坑.准备把踩得这些坑记录下来. 自动化测试最基础的就是打开浏览器然后让Windows窗口最大化. 一开始百度了好多窗口最大化的方法,最常用的是: WebDriv ...

  7. web自动化_浏览器驱动chromedriver安装方法(适用RF框架/Selenium/Appium)

    在进行UI自动化时,打开浏览器是第一步,这就必须要安装浏览器的驱动,chrome浏览器需要安装chromedriver,下载地址:http://chromedriver.storage.googlea ...

  8. Selenium_python自动化跨浏览器执行测试(简单多线程案例)

    发生背景: 跨浏览器测试是功能测试的一个分支,用以验证web应用在不同浏览器上的正常工作,通常情况下,我们都期望web类应用能够被我们的用户在任何浏览器上使用,例如有的人喜欢IE浏览器上使用,有的人喜 ...

  9. Selenium2+python自动化-操作浏览器基本方法

    前言 从这篇开始,正式学习selenium的webdriver框架.我们平常说的 selenium自动化,其实它并不是类似于QTP之类的有GUI界面的可视化工具,我们要学的是webdriver框架的A ...

  10. Selenium2+python自动化61-Chrome浏览器(chromedriver)【转载】

    前言 selenium2启动Chrome浏览器是需要安装驱动包的,但是不同的Chrome浏览器版本号,对应的驱动文件版本号又不一样,如果版本号不匹配,是没法启动起来的. 一.Chrome遇到问题 1. ...

随机推荐

  1. 打印三位数的水仙花数Java

    public class Flower{ //水仙花数就是一个 个位数的立方+十位数的立方+百位数的立方=这个三位数 //153 = 1*1*1+5*5*5+3*3*3 public static v ...

  2. 关于 risrqnis

    这道题里最有用的( Range Insert Subset Range Query [n?] In Set 破案了 我那五个点是因为维护不知道有什么用的东西炸了 删了就过了 题面 [JRKSJ R4] ...

  3. python 实现AES加解密

    AES 只是个基本算法,实现 AES 有几种模式,主要有 ECB.CBC.CFB 和 OFB  CTR,直接上代码,此处为AES加密中的CBC模式,EBC模式与CBC模式相比,不需要iv. impor ...

  4. jdk调度任务线程池ScheduledThreadPoolExecutor工作原理解析

    jdk调度任务线程池ScheduledThreadPoolExecutor工作原理解析 在日常开发中存在着调度延时任务.定时任务的需求,而jdk中提供了两种基于内存的任务调度工具,即相对早期的java ...

  5. XSS漏洞利用案例实验

    前言 此为XSS漏洞学习笔记,记录XSS的学习过程,方便今后复习使用,有写的不好的地方请见谅,大佬勿喷. GET型XSS利用 攻击流程 攻击实现 以pikachu网站的反射型XSS(GET)为例 攻击 ...

  6. PostgreSQL(02): PostgreSQL常用命令

    目录 PostgreSQL(01): Ubuntu20.04/22.04 PostgreSQL 安装配置记录 PostgreSQL(02): PostgreSQL常用命令 PostgreSQL 常用命 ...

  7. Windowsのcmd命令

    Windowsのcmd命令 网络操作: ipconfig命令: ipconfig -all 查看网络信息 ipconfig -release 释放ip/tcp ipconfig -renew 重新获取 ...

  8. [WPF]DataContext结果不显示

    namespace DataContext_ItemSource_Demo { public class Person { public string Name; } public class Vie ...

  9. sikulix___自动化办公___重复性_机械性_的电脑操作___python脚本___Java运行环境下德jar包完成自动化测试相关___截图编程控制键盘鼠标

    sikulix___自动化办公___重复性_机械性_的电脑操作___python脚本___Java运行环境下德jar包完成自动化测试相关___截图编程控制键盘鼠标 应用场景: 公司内的大佬更改了xml ...

  10. 除了Navicat和DBeaver,还有没有免费又好用的数据库管理/SQL工具推荐

    很多国内SQL学习者和开发者对Navicat.DBeaver等国外数据库管理工具已经很熟悉了.但是,有没有比他们更适合SQL开发者的数据库管理/SQL工具呢?这里,笔者结合自己的调研来聊一下. 笔者做 ...