首页 > 其他分享 >selenium爬取异步加载的网站

selenium爬取异步加载的网站

时间:2023-04-18 10:32:17浏览次数:32  
标签:异步 option selenium argument 爬取 xhr add logs log

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

selenium爬取异步加载的网站_模拟点击

对于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)

标签:异步,option,selenium,argument,爬取,xhr,add,logs,log
From: https://blog.51cto.com/u_13488918/6202565

相关文章

  • 批量爬取TXT文本
    importreimportos #导入模块importthreadingimportpymysql#连接数据框,创建表db=pymysql.connect(host='localhost',user='root',password='1234',database='旅游�......
  • LABjs异步加载组件
    加载外部js的方法大致有这么几种:方法说明XHREval     通过Ajax方式获取代码,并通过eval方式执行代码。XHRInjection     通过Ajax方式获取代码,并在页面上创建一个script元素,将Ajax取得的代码注入。ScriptinIframe      通过iframe加载js。Scr......
  • selenium登录cnblogs、抽屉半自动点赞、xpath的使用、打码平台使用、scrapy介绍
    昨日回顾#1beautifulsoup4使用-xml解析库,用它来解析爬回来的html内容,从中找出我们需要的内容#2遍历文档树-.的使用soup.html.body.p.a-获取属性对象.attrs.get('href')-获取文本对象.textstringstrings-子节点,父节点,兄......
  • 爬取的数据存mysql中、加代理,cookie,header,加入selenium、布隆过滤器、scrapy-redis实
    上节回顾#1scrapy架构 -爬虫:写的一个个类-引擎: -调度器:排队,去重-下载器-pipline-下载中间件-爬虫中间件#2命令 -scrapystartproject项目名-scrapygensipder爬虫名网址-scrapycrawl爬虫名字-run.py#......
  • 记录selenium,python自动化测试中的chromedriver.exe地址和打开后自动关闭浏览器问题
    selenium的官方地址为:https://selenium-python.readthedocs.io/index.html镜像地址:https://npmmirror.com/#导入webdriverfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy#调用键盘按键操作时需要引入的Keys包fromselenium.webdriver.common.k......
  • JavaScript中 处理异步的几种方法
    1.回调函数回调(callback)是一个函数被作为一个参数传递到另一个函数里,在那个函数执行完后再执行。假定有两个函数f1和f2,f2等待f1的执行结果,f1()–>f2();如果f1很耗时,可以改写f1,把f2(箭头函数)写成f1的回调函数:functionf1(callback){setTimeout(()=>{letname='小明'......
  • 同步异步阻塞费阻塞
       同步和异步是内核代码实现的方式阻塞和非阻塞:获取结果的方式(等待还是不等待)......
  • js 异步任务执行顺序问题
    js是单线程的(非阻塞的),实现方法就是事件循环;分同步任务和异步任务;newPromise((resolve,reject)=>{resolve(1)console.log('log1')}).then(()=>{console.log('log2')})console.log('log3')setTimeout(()=>......
  • pytest+selenium+allure
     您可以使用pip安装SeleniumWebDriver:```pipinstallselenium```3.安装pytest您可以使用pip安装pytest:```pipinstallpytest```4.安装pytest-xdistpytest-xdist是一个pytest插件,用于并行运行测试。您可以使用以下命令安装:```pipinstallpytest-xdist......
  • Java异步同步回调
    同步回调:打印结果:123publicinterfaceResult{voidcallBack();}publicstaticvoidmain(String[]args)throwsInterruptedException{Entityentity=newEntity();entity.task(()->System.out.println("2")......