首页 > 解决方案 > 随着时间的推移,Python Selenium 刮板变得明显变慢

问题描述

我正在使用 python、selenium 和 TOR 的组合来抓取一个网站。

抓取工作正常,但随着时间的推移会变得非常慢,最初每分钟最多抓取 30 页,然后在几分钟的时间范围内缓慢但稳定地下降到每分钟 4-5 页左右。

我目前不关心解析网页的内容。我将在稍后阶段执行此操作,因此这超出了此问题的范围。

这是我的代码:

import requests
from stem import Signal
from stem.control import Controller
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


def get_tor_session():
    session = requests.Session()
    # Tor uses the 9050 port as the default socks port
    session.proxies = {'http':  'socks5://127.0.0.1:9050',
                       'https': 'socks5://127.0.0.1:9050'}
    #session.headers = {'User-Agent': 'Mozilla/5.0'}
    session.headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux i686; G518Rco3Yp0uLV40Lcc9hAzC1BOROTJADjicLjOmlr4=) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36','Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8','Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3','Accept-Encoding': 'gzip, deflate, sdch','Accept-Language': 'en-US,en;q=0.8','Connection': 'keep-alive'}
    return session



# signal TOR for a new connection 
def renew_connection():
    with Controller.from_port(port = 9051) as controller:
        controller.authenticate(password="16:8F6BA4CFC409D432607A853D139F3FFE43A1B77E4893BEA3CE7F63DA27")
        controller.signal(Signal.NEWNYM)


chrome_options = Options()
chrome_options.add_argument("--proxy-server=socks5://127.0.0.1:9050")
url = "https://www.targesite.com/"
driver = webdriver.Chrome(options=chrome_options)

for i in range(1,1000000,1):
    renew_connection()
    session = get_tor_session()
    finalUrl = url + str(i) + "/"
    driver.get(finalUrl)
    f=open("C:\\outputs\\" + str(i) +".txt", "a+", encoding="utf-8")
    f.write(driver.page_source)
    f.close()

我没有太多在 python 中抓取的经验,而且我的 python 总体上相当生疏——因此我不确定是什么导致了这些减速。我的问题是:

我能做些什么来避免这些减速?使用“正确”的代码,我应该能够保持每分钟 30 页的高初始抓取速度,或者不是?

标签: pythonselenium-webdriverweb-scraping

解决方案


推荐阅读