selenium 之 selenium-wire获取浏览器Network请求和响应 踩坑经验教训

2,339 阅读1分钟

前言:

   现在的公司为了不被爬虫,不断的改版前后端数据交互方式,但俗语有说:道高一尺,魔高一丈;对于常见
   的:iframe、svg、接口交互(Network请求和响应) selenium、网路上的各种大神都有出对应的对策,
   本文章,主要介绍 获取浏览器Network请求和响应 的方法以及经验教训(滴泪。。。)
复制代码

正文:

前置:

这里以抓取喜马拉雅接口数据为例,目标url:https://www.ximalaya.com/sound/148249100 获取Network请求和响应

selenium-wire抓取Network数据包

安装:

pip install selenium-wire

ps:selenium 版本貌似要大于4.1.0 下使用比较好

上代码

from seleniumwire import webdriver
from selenium.webdriver.chrome.service import Service


# chromedriver 路径配置
driverP = Service(r'xxxx/xxxxx/chromedriver的存放路径')


# ChromeOptions 配置相关
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')


driver = webdriver.Chrome(options=option, service=driverP)

base_url = "https://www.ximalaya.com/sound/148249100"

driver.get(base_url)

for request in driver.requests:
    if request.response:
        # print("request.url", request.url)
        if "/bdsp/album/pay" in request.url:
            # print(request.response.body)
            _content = gzip.decompress(request.response.body).decode('utf-8')
            # 获取接口返回内容
            try:
                json_content = json.loads(_content)
                logger.info("转json 成功,结果{}".format(json_content))
                return json_content
            except:

                logger.info("转json 失败,结果{}".format(_content))
                return _content

_content = "None"
logger.info("seleniumwire_network,for 循环完了,结果:{}".format(_content))

driver.quit()

没看错 ,就只有这么简单的一段!!相比 Browsermob-Proxy 是不是 更香了?同样,在mac/linux下使用没有任何问题的,但在windows 上,就有让人无语了

坑1、 致命伤!!!如果是在vpn(自行百科)情况下使用selenium-wire 恰好 运行环境是 win 11 以下 90%机率出现异常,详细可以看: blog.csdn.net/qq_36991535…

ps:换句话说,vpn + selenium-wire + win11 下运行,是没问题的(惊呆了没)