【发布时间】: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