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
相关推荐
weixin_440730508 小时前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
天赐范式8 小时前
天赐范式第181天:让视图开始切换——PBFT视图切换与从safety到liveness的跨越
python·pbft·数字生命·天赐范式·动态运行时·拜占庭容错
sugarzhangnotes8 小时前
【无标题】
开发语言·人工智能·python
weixin_447195299 小时前
【无标题】
pytorch·python
迅猛龙办公室9 小时前
Python实现简单的人名对话
python
阿坨9 小时前
firestart:一行命令启动你的日常应用和网页
python·pypi·cli·click
老歌老听老掉牙9 小时前
麻花钻切屑形态演变的力学机制与临界条件分析
python·算法·钻头
ZhangJun959 小时前
从零写一个类鲁大师的硬件检测小工具,软件附上,可直接使用
windows·测试工具·电脑·笔记本电脑·硬件架构
happylifetree10 小时前
Python18(补充):练习
python
weixin_4166679610 小时前
银河麒麟V10看门狗试验-1
网络·chrome·python