selenium爬取异步加载的网站

文章介绍了在使用Selenium爬虫时,面对xhr加载内容的网页,如何通过等待xhr请求完成或直接获取响应内容来定位元素。关键点包括设置浏览器选项,定位动态元素,以及编写函数等待特定xhr请求。示例代码展示了如何获取xhr日志并处理请求。
摘要由CSDN通过智能技术生成

为了便利化使用selenium驱动浏览器进行操作,遇到一个网页,大部分内容都是通过xhr请求后再通过前端js处理显示,带来的一个问题就是,采用显示等待无法准确的定位到需要的节点。因此,需要考虑采用判断xhr请求是否完成后再进行定位,或者直接获取xhr请求返回内容的做法。

对于selenium爬虫来说,以下是几个需要注意的要点:

1、确定好爬取目标和数据结构:在开始爬取过程前,需要明确爬取目标和目标数据的结构。

2、使用合适的浏览器驱动:selenium需要一个浏览器驱动来控制浏览器,需要根据自己使用的浏览器版本下载相应版本的浏览器驱动。

3、掌握好定位元素的方法:在爬取网页内容时,需要掌握好如何定位需要爬取的元素,使用selenium提供的定位方法,如通过id、name、class、xpath等。

4、设置合适的间隔时间:避免爬取过快导致封IP或者被识别为恶意爬虫,需要设置合适的间隔时间。

5、处理网页加载时的动态内容:对于需要模拟点击、滚动等动作才能显示出的网页内容,需要使用selenium提供的模拟点击、滚动等方法。

总之,需要结合具体需求和网站特性来合理应用selenium爬虫技术。

直接上代码:

import json
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
import os,time

配置浏览器启动参数

def get_log_options():
    option = webdriver.ChromeOptions()
    option.add_argument('--no-sandbox')
    #option.add_argument('--headless')  # 设置无头浏览
    option.add_argument("--disable-extensions")
    option.add_argument('--disable-infobars') # 禁用浏览器正在被自动化程序控制的提示
    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,
    })
    option.add_experimental_option('prefs',{
        #不弹出去请求
        'profile.default_content_settings.popups':0,
        #设置默认下载文件目录
        'download.default_directory':save_folder,
        # 禁止提示
        'profile.default_content_setting_values':{
            'notifications': 2
        }
    })
    return option
 
    
def get_caps():
    caps = DesiredCapabilities.CHROME
    caps['loggingPrefs'] = {
        'browser': 'ALL',
        'performance': 'ALL',
    }
    caps['perfLoggingPrefs'] = {
        'enableNetwork': True,
        'enablePage': False,
        'enableTimeline': False
    }
    return caps

# 获取日志中的xhr结果
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

# 根据id获取返回结果
def get_xhr_body(driver, requestId):
    response_body = driver.execute_cdp_cmd('Network.getResponseBody', {'requestId': requestId})
    return response_body

考虑部分xhr请求较慢,增加一个判断指定请求是否完成的函数来判断执行情况。

# 等待直到某个xhr出现,返回整个异步情况吧
def wait_until_xhr_do(url='',limit = 10):
    tick = 0
    while tick < limit:
        logs = get_xhr_logs(chrome)
        if url == '':
            if len(logs) > 0:
                return logs
        else:
            for log in logs:
                if url in logs['params']['response']['url']:
                    return logs
        tick = tick + 1
    return []

最终案例参考:

if __name__ == '__main__':
    # 使用工具类来获取options配置,而不是平时的webdriver.ChromeOptions()方法
    options = get_log_options()
    # 使用工具类来获取caps
    desired_capabilities = get_caps()
    # 这里也可以对options和caps加入其他的参数,比如代理参数等
    chrome = webdriver.Chrome(options=options, desired_capabilities=desired_capabilities)
    chrome.get("http://jshk.com.cn/")  # "https://www.baidu.com/"
    chrome.maximize_window()
    
    # 点击下一页
    el= chrome.find_element_by_xpath('//button[@class="btn-next"]')
    el.click()
    # 执行等待
    logs = wait_until_xhr_do()
    # 输出结果
    if len(logs) > 0:
        print(logs[0]['params']['response']['url'])

        body = get_xhr_body(chrome, logs[0]['params']['requestId'])
        # 使用eval转换遇到null会有问题,改为使用Json转换
        response = json.loads((body['body']))
        print(response)
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值