python利用chrome和selenium访问网站

python利用chrome和selenium访问网站

risenarrow
2025-04-15 21:52

第一步

安装chrome和ChromeDriver


chrome版本要和ChromeDriver版本一致

ChromDriver下载地址 https://sites.google.com/chromium.org/driver/downloads



第二步

安装pychrome和Selenium


pip install pychrome

pip install selenium


第三部


打开chrome—dev-tools

/software/chrome/chrome-linux64/chrome --remote-debugging-port=9222 --user-data-dir=/software/utils/pychrome --no-sandbox --headless=new --remote-allow-origins=* > output.log 2>&1 &

也可以放在一个脚本文件,然后用nohup命令启动

nogup /usr/bin/sh chromedev.sh


第四部

编写python代码

import pychrome
import json

# 连接到 Chrome 调试实例
browser = pychrome.Browser(url="http://localhost:9222")
tabs = browser.list_tab()  # 默认选择第一个标签页
tab = tabs.pop()
tab.start()
tab.Page.enable()
# 启用 Network 域
tab.Network.enable()
target_url = "https:/www.baidu.com/"
tab.Page.navigate(url=target_url)
# 存储响应数据的容器
response_data = {}

def get_response_body(request_id):
    response_body =  tab.Network.getResponseBody(requestId=request_id)
    return response_body;


def is_json(data):
    try:
        json.loads(data)
        return True
    except json.JSONDecodeError:
        return False

def on_request_finished(**kwargs):
    request_id = kwargs.get('requestId')
    url = kwargs.get("url")
    response_body = get_response_body(request_id);
    with open('req_json.txt', 'a') as file:
        if is_json(response_body["body"]):
            info = json.loads(response_body["body"])
          if info["aweme_detail"]["video"]["play_addr_h264"] is not None:
                print("\r\n\r\n\r\n\r\n", file=file)
                print("url: {}".format(url), file=file)
                print("Request ID: {}".format(request_id), file=file)
                print("Response Body: {}".format(info["aweme_detail"]["video"]["play_addr_h264"]), file=file)
tab.Network.requestWillBeSent = on_request_finished


# 开始监听

tab.wait(20)  # 监听10秒(按需调整)

# 输出结果
print(json.dumps(response_data, indent=2))