📜  python 获取网站 chrome 网络选项卡 - Python (1)

📅  最后修改于: 2023-12-03 15:34:13.495000             🧑  作者: Mango

Python获取网站Chrome网络选项卡

在开发Web应用程序时,我们需要获取网站Chrome网络选项卡以进行网络分析和调试。Python是一种极其适合数据获取和处理的编程语言,可以使用Python来获取Chrome网络选项卡。

方案一
第一步:安装必需的库

使用该方法前,需要安装chromedriver和selenium库。安装方法如下:

pip install selenium

在安装前,请确保您的电脑已经安装Chrome浏览器,并根据需要,下载并配置安装Chrome浏览器对应版本的浏览器驱动程序(chromedriver驱动程序下载地址)。

第二步:编写Python代码
from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument("--headless") # 无头模式:不启动GUI界面,节省资源
options.add_argument("--no-sandbox") # 沙箱模式:禁用沙箱才能在容器中运行
options.add_argument("--disable-dev-shm-usage") # 使用 /dev / shm 作为临时目录,否则在一些系统中可能会不稳定

driver = webdriver.Chrome(options=options)

# 使用访问的URL作为参数获取网络选项卡
driver.get('http://www.example.com')
performance = driver.execute_script('return window.performance.getEntries();')

print(performance)
driver.quit()
第三步:运行Python代码

在终端上运行Python代码,即可获取URL对应的Chrome网络选项卡指标。

python get_network_tab.py
方案二
第一步:安装必需的库

使用该方法前,需要安装pychrome库。安装方法如下:

pip install pychrome

在安装前,请确保您的电脑已经安装Chrome浏览器,并根据需要,下载并配置安装Chrome浏览器对应版本的浏览器驱动程序(chromedriver驱动程序下载地址)。

第二步:编写Python代码
import json
import pychrome

def process_entry_type(requestId, entry):
    if entry['entryType'] == "resource":
        print(requestId, entry)
        

browser = pychrome.Browser(url="http://127.0.0.1:9222")
tab = browser.list_tab()[0]
tab.start()

# 监听每一个HTTP请求完成的事件
tab.Network.requestWillBeSent = process_entry_type
tab.Network.enable()

# 使用访问的URL作为参数打开指定页面
tab.Page.navigate(url="http://www.example.com", _timeout=5)
tab.wait(5)

# 关闭选项卡并退出浏览器
tab.stop()
browser.close_tab(tab)
第三步:运行Python代码

在终端上运行Python代码,即可获取URL对应的Chrome网络选项卡指标。

python get_network_tab.py

以上就是两种获取网站Chrome网络选项卡的方法,您可以根据自己的需求选择合适的方法。