共计 1620 个字符,预计需要花费 5 分钟才能阅读完成。
自动化
==Splinter 是对 selenium 的形象,更高级用法 ==
Splinter
无关 Splinter && selenium 博客
Playwright 自动化模仿浏览器点击
palywright 相干文章
playwright 文档
# 装置 playwright 库
pip install playwright
# 装置浏览器驱动文件(装置过程略微有点慢)python -m playwright install
# 命令行键入 --help 可看到所有选项
python -m playwright codegen
-o:将录制的脚本保留到一个文件
--target:规定生成脚本的语言,有 JS 和 Python 两种,默认为 Python
-b:指定浏览器驱动
playwright demo
python -m playwright codegen –target python -o ‘my.py’ -b chromium https://www.baidu.com
同步顺次关上三个浏览器,返回 baidu 搜寻,截图后退出。
from playwright import sync_playwright
with sync_playwright() as p:
for browser_type in [p.chromium, p.firefox, p.webkit]:
browser = browser_type.launch()
page = browser.newPage()
page.goto('https://baidu.com/')
page.screenshot(path=f'example-{browser_type.name}.png')
browser.close()
异步异步操作可联合 asyncio 同时进行三个浏览器操作。
import asyncio
from playwright import async_playwright
async def main():
async with async_playwright() as p:
for browser_type in [p.chromium, p.firefox, p.webkit]:
browser = await browser_type.launch()
page = await browser.newPage()
await page.goto('http://baidu.com/')
await page.screenshot(path=f'example-{browser_type.name}.png')
await browser.close()
asyncio.get_event_loop().run_until_complete(main())
挪动端更厉害的是,playwright 还可反对挪动端的浏览器模仿。上面是官网文档提供的一段代码,模仿在给定地理位置上手机 iphone 11 pro 上的 Safari 浏览器,首先导航到 maps.google.com,而后执行定位并截图。
from playwright import sync_playwright
with sync_playwright() as p:
iphone_11 = p.devices['iPhone 11 Pro']
browser = p.webkit.launch(headless=False)
context = browser.newContext(
**iphone_11,
locale='en-US',
geolocation={'longitude': 12.492507, 'latitude': 41.889938},
permissions=['geolocation']
)
page = context.newPage()
page.goto('https://maps.google.com')
page.click('text="Your location"')
page.screenshot(path='colosseum-iphone.png')
browser.close()
正文完