Selenium获取Network数据

前言

为解决从Selenium中获取Network接口数据,潜心研究了一小会儿,遂有此文

基本看这篇文章的,多多少少都跟spider 沾亲带故。所以直接进入正题。

只想要代码,文章前边自取

想看长篇大论,先看这篇 【Selenium】控制当前已经打开的 chrome浏览器窗口(高级版)

应用场景

Chrome浏览器 -> 开发者工具 -> Network 中所有的数据包,我要全部拿下来。

举个例子🌰

网站通过XHR异步加载数据,然后再渲染到网页上。而通过Selenium去获取渲染后的数据,是同HTML打交道的

异步加载返回数据是json文件的,有时渲染在网页上,不一定是完整的json文件中的数据;最重要的是,json文件解析起来很方便

通过selenium去拿网页数据,往往是两个途径:

selenium.page_source,通过解析HTML

通过中间人进行数据截获,数据源是啥就是啥

这两种方法各有利弊,但是这篇文章就可以将他们相结合起来了,实在是妙啊!

可能你会有疑惑👀?直接使用requests去请求不就完事了,

请你想一下,我这都使用上selenium了,你觉得我还会去使用requests再多请求一遍吗???

完整代码

Selenium获取Network

这里指定9527端口打开浏览器,也可以不指定

python 复制代码
# -*- coding: utf-8 -*-
# @Time   : 2022-08-27 11:59
# @Name   : selenium_cdp.py

import json
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options

caps = {
    "browserName": "chrome",
    'goog:loggingPrefs': {'performance': 'ALL'}  # 开启日志性能监听
}
options = Options()
options.add_experimental_option("debuggerAddress", "127.0.0.1:9527")  # 指定端口为9527
browser = webdriver.Chrome(desired_capabilities=caps, options=options)  # 启动浏览器
browser.get('https://blog.csdn.net/weixin_45081575')  # 访问该url


def filter_type(_type: str):
    types = [
        'application/javascript', 'application/x-javascript', 'text/css', 'webp', 'image/png', 'image/gif',
        'image/jpeg', 'image/x-icon', 'application/octet-stream'
    ]
    if _type not in types:
        return True
    return False


performance_log = browser.get_log('performance')  # 获取名称为 performance 的日志
for packet in performance_log:
    message = json.loads(packet.get('message')).get('message')  # 获取message的数据
    if message.get('method') != 'Network.responseReceived':  # 如果method 不是 responseReceived 类型就不往下执行
        continue
    packet_type = message.get('params').get('response').get('mimeType')  # 获取该请求返回的type
    if not filter_type(_type=packet_type):  # 过滤type
        continue
    requestId = message.get('params').get('requestId')  # 唯一的请求标识符。相当于该请求的身份证
    url = message.get('params').get('response').get('url')  # 获取 该请求  url
    try:
        resp = browser.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})  # selenium调用 cdp
        print(f'type: {packet_type} url: {url}')
        print(f'response: {resp}')
        print()
    except WebDriverException:  # 忽略异常
        pass
相关推荐
李妍.2 小时前
02Numpy基础(上)
开发语言·python
TheBestRucy2 小时前
Python 九阳神功之贰:面向对象(下)
开发语言·python
IT小白杨2 小时前
工程视角下的浏览器环境API:资源模型、权限审计与MCP实践
大数据·经验分享·selenium·chrome devtools·安全架构·指纹浏览器
2601_965958462 小时前
口腔黏膜脱皮超2周未愈建议及时就医
人工智能·python
随风而飘1863 小时前
KEITHLEY吉时利 2400 数字源表
人工智能·功能测试·科技·测试工具
微小冷3 小时前
在不同空间中展示数据(欧式、球面、庞加莱圆盘)
python·双曲空间·微分几何·geomstats·庞加莱圆盘·球面
weixin_431600444 小时前
Agent Workflow 学习向:Code 节点,比模板更强的变量加工
后端·python·学习·ai·
讲温控就好了4 小时前
从医疗影像到能源存储——芯片冷却温控技术的跨行业赋能
人工智能·python·能源
DeepVisionary4 小时前
从 Qwen3.8-27B 把原生多模态、原生 FP8、桌面级 Agent 三件事一次集齐,看开源大模型的“工业化拐点“
python·自动化
固定资产管理系统软件5 小时前
商务局RFID固定资产管理系统的应用价值与落地要点解析
大数据·python