获取xhr请求工具类

import json
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities


def get_xhr_logs(chrome):
    log_xhr_array = []
    for typelog in chrome.log_types:
        perfs = chrome.get_log(typelog)
        for row in perfs:
            log_data = row
            message_ = log_data['message']
            try:
                log_json = json.loads(message_)
                log = log_json['message']
                if log['method'] == 'Network.responseReceived':
                    # 去掉静态js、css等,仅保留xhr请求
                    type_ = log['params']['type']
                    if type_ == "XHR":
                        log_xhr_array.append(log)
            except:
                pass
    return log_xhr_array


def get_log_options():
    option = webdriver.ChromeOptions()
    option.add_argument('--no-sandbox')
    option.add_argument('--headless')
    option.add_argument("--disable-extensions")
    option.add_argument("--allow-running-insecure-content")
    option.add_argument("--ignore-certificate-errors")
    option.add_argument("--disable-single-click-autofill")
    option.add_argument("--disable-autofill-keyboard-accessory-view[8]")
    option.add_argument("--disable-full-form-autofill-ios")
    option.add_argument('user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:55.0) Gecko/20100101 Firefox/55.0')
    option.add_experimental_option('w3c', False)
    option.add_experimental_option('perfLoggingPrefs', {
        'enableNetwork': True,
        'enablePage': False,
    })
    return option


def get_caps():
    caps = DesiredCapabilities.CHROME
    caps['loggingPrefs'] = {
        'browser': 'ALL',
        'performance': 'ALL',
    }
    caps['perfLoggingPrefs'] = {
        'enableNetwork': True,
        'enablePage': False,
        'enableTimeline': False
    }
    return caps

使用:

# 拦截进入详情页面,使用selenium绕过反爬
class SeleniumMiddlewareDetail:
    def process_response(self, request, response, spider):
        if request.meta['code'] == 1:
            chrome = spider.chrome
            chrome.get(request.url)
            # network日志
            logs = get_xhr_logs(chrome)
            return HtmlResponse(url=spider.chrome.current_url,
                                body=bytes(json.dumps(logs), encoding='utf8'),
                                encoding="utf8",
                                request=request)

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

文子阳

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值