【问题标题】:undetected_chromedriver works too slowundetected_chromedriver 工作太慢
【发布时间】:2022-06-26 23:49:31
【问题描述】:

我正在尝试抓取一个唯一域的不同网站。我有以下 URL 结构:

URL = 'https://somewebsite.eu/id/{}'.format(ID) 变量 ID 采用许多值。该网站受 Cloudflare 系统保护,因此我决定使用 selenium 和未检测到的 chrome 驱动程序绕过它。所有其他方法,例如带有会话的请求和 cfcscrape 都不适用于该网站。

由于我需要解析许多具有相似 URL 结构的页面,我决定对 ID 变量的所有值使用循环。

import pandas as pd
import numpy as np
import requests
import selenium

from undetected_chromedriver import Chrome 
from selenium.webdriver.chrome.options import Options
import time

def extracting_html_files_v11(ids):
    options = Options()
    options.add_argument("start-maximized")
    for x in ids:
        start_time = time.time()
        browser = Chrome(option = options)
        print('initialization of the browser')
        url = 'https://somewebsite.eu/id/{}/'.format(x)
        print(url)
        browser.get(url) 
        print('the page was downloaded')
        
        time_to_wait = np.random.uniform(low = 7, high = 10)
        time.sleep(time_to_wait)

        file_name = 'data_8000_9000/case_{}.html'.format(x)
        with open(file_name, 'w', encoding="utf-8") as f:
            f.write(browser.page_source)
        print('the file was saved')
        browser.quit()
        print('the browser was quited')
        print("--- %s seconds ---" % (time.time() - start_time))
        for i in range(3):
            print('_____')

但是,此过程需要的时间太长。每次启动浏览器后,我需要等待大约 5 秒钟,让 Cloudflare 让我下载页面(这就是我有 time.sleep(time_to_wait) 的原因)。代码可以优化吗?我应该考虑并行编程或类似的东西吗? (我完全是并行进程的初学者)。

【问题讨论】:

  • 不建议使用多线程或处理,网站可能会认为您正在对它们进行 DDoS 攻击并触发更多保护

标签: python selenium-webdriver web-scraping selenium-chromedriver undetected-chromedriver


【解决方案1】:

为什么要多次这样做? 浏览器 = Chrome(选项 = 选项)

只需在例程之外执行一次,并将浏览器作为参数传递

还有:你可以调查的东西,虽然可能工作量太大。 在 10 页上打开新标签,无需等待结果,然后循环浏览每个标签并执行您需要做的事情。那么每个标签应该重叠下载吗?

selenium 4 有用于启动选项卡和切换选项卡的新功能,您必须仔细阅读。

【讨论】:

    猜你喜欢
    • 2022-10-30
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2011-06-01
    • 2019-07-14
    相关资源
    最近更新 更多