python网页自动化(二)

参考链接:此链接太长

前言

之前介绍过使用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

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Greate AUK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值