参考链接:此链接太长
前言
之前介绍过使用selenium来进行网页自动化,但是里面的“id”还有“点击”需要自己一个个地找、敲,所以有点麻烦,这里用微软的自动化神器playwright。
1.安装
pip3 install playwright
python3 -m playwright install //安装浏览器,这一步持续时间较长
安装时会显示如下:
Downloading chromium v833159 - 120.3 Mb [====================] 100% 0.0s
chromium v833159 downloaded to /home/Jack/.cache/ms-playwright/chromium-833159
Downloading firefox v1221 - 72.7 Mb [====================] 100% 0.0s
firefox v1221 downloaded to /home/Jack/.cache/ms-playwright/firefox-1221
Downloading webkit v1402 - 77.1 Mb [====================] 100% 0.0s
2.操作
这会打开playwright默认的浏览器,然后将你对浏览器的操作记录,以python的格式在终端打印出来
python -m playwright codegen
进一步:
python3 -m playwright codegen --target python -o 'output.py' -b chromium https://www.baidu.com
会打开指定的浏览器chromium(还有一个是firefox),然后将生成的python格式的文件以output.py作为输出。
那么下次只需要打开output.py,直接运行该文件即可。
eg:output.py
from playwright import sync_playwright
def run(playwright):
browser = playwright.chromium.launch(headless=False)
context = browser.newContext()
# Open new page
page = context.newPage()
# Go to https://www.baidu.com/
page.goto("https://www.baidu.com/")
# Click input[name="wd"]
page.click("input[name=\"wd\"]")
# Fill input[name="wd"]
page.fill("input[name=\"wd\"]", "hub")
# Click text="系统"
# with page.expect_navigation(url="https://www.baidu.com/s?ie=utf-8&f=3&rsv_bp=1&rsv_idx=1&tn=baidu&wd=hub%E7%B3%BB%E7%BB%9F&fenlei=256&rsv_pq=d486c87d00003b45&rsv_t=c400wLOUls2v9Lp7XXRjKnSo1R4CyWxfRUU1RWG76lp7vYXCCHpdfzoACUw&rqlang=cn&rsv_enter=1&rsv_dl=ts_0&rsv_sug3=4&rsv_sug1=2&rsv_sug7=100&rsv_sug2=1&rsv_btype=i&prefixsug=hub&rsp=0&inputT=2523&rsv_sug4=3439"):
with page.expect_navigation():
page.click("text=\"系统\"")
# Close page
page.close()
# ---------------------
context.close()
browser.close()
with sync_playwright() as playwright:
run(playwright)
3.备注
查看相关说明:python3 -m playwright codegen --help
Usage: index codegen [options] [url]
open page and generate code for user actions
Options:
-o, --output <file name> saves the generated script to a file
--target <language> language to use, one of javascript, python, python-async,
csharp (default: "python")
-h, --help display help for command
Examples:
$ codegen
$ codegen --target=python
$ -b webkit codegen https://example.com
上一篇:https://blog.csdn.net/wxkhturfun/article/details/110748689