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
相关推荐
李航19836 小时前
用 DeepDraw 几何引擎开发建筑设计软件(五):创建选择工具
python·3d
Metaphor6926 小时前
使用 Python 设置 Excel 行列自适应 【代码示例】
python·excel
花酒锄作田15 小时前
FastAPI 使用 session 认证
python·fastapi
lsswear15 小时前
Python 并发 线程
开发语言·python
蒲公英内测分发16 小时前
App 更新一次就换一个二维码?智能硬件配套 App 的版本和下载入口怎么管理
人工智能·测试工具·智能家居·智能硬件
Ivanqhz16 小时前
MLIR OpBuilder
开发语言·python·mlir
威联通安全存储17 小时前
TS-h2287XU-RP 在家电制造总装与质检数据场景的部署
python·制造
泡泡鱼(敲代码中)18 小时前
Python 字符串 str 完整学习笔记
python·学习
troy12818 小时前
Python 基础语法(八):Web 后端开发、数据分析与可视化、网络爬虫、人工智能 / 大模型应用
前端·python·数据分析
我不会起名字32219 小时前
一天一道算法题(34):回溯法的经典例题(子集)
java·数据结构·python·算法·golang·深度优先·力扣