Playwright是一个强大的Python库,仅用一个API即可自动执行Chromium、Firefox、WebKit等主流浏览器自动化操作。
安装包:pip install playwright
安装浏览器驱动python -m playwright install
CMD中输入:python -m playwright help
查看帮助信息
录制脚本:python -m playwright codegen https://www.baidu.com
录制脚本复杂命令
# 我们通过下面命令打开 Chrome 浏览器开始录制脚本
# 指定生成语言为:Python(默认Python,可选)
# 保存的文件名:mikezhou.py(可选)
# 浏览器驱动:webkit(默认webkit,可选)
# 最后跟着要打开的目标网站(默认仅仅是打开浏览器,可选)
python3 -m playwright codegen --target python -o 'mikezhou.py' -b chromium https://www.baidu.com
录制实例代码
from playwright.sync_api import Playwright, sync_playwright, expect
def run(playwright: Playwright) -> None:
browser = playwright.chromium.launch(headless=False,slow_mo=1000)
context = browser.new_context()
page = context.new_page()
page.goto("https://www.baidu.com/")
page.locator("#kw").click()
page.locator("#kw").fill("阿森纳")
page.get_by_role("button", name="百度一下").click()
page.screenshot(path='1.jpg',full_page=True)
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
slow_mo=1000 为延时参数,可以理解为sleep。
full_page=Ture 为截取长图,默认为False。
浏览器非静默运行browser = playwright.chromium.launch(headless=False)
浏览器静默运行:browser = playwright.chromium.launch(headless=True)
浏览器默认语言为英语:context = browser.new_context(locale='en-US')