python - 随着时间的推移,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 页的高初始抓取速度,或者不是?
解决方案
推荐阅读
- php - 我想将字符串的某些部分从“此匹配”删除为“另一个匹配”
- angular - 使用 NgRX 实体标准化 Api 响应
- javascript - Highcharts - 气泡在不退出图表的情况下失去焦点
- kubernetes - 基于客户端会话而不是客户端 IP 的 kubernetes 中的会话关联
- linux - ubuntu中的脚本同时获取CPU温度和CPU使用率并保存到文件
- wordpress - 如果产品类别是“商店提货”,则在产品标题前的 woocommerce 产品页面上回显“销售”
- node.js - 尽管保存在数据库中,但只检索了一半的猫鼬模式
- javascript - 无法获取 php 请求的 html 元素的值
- plc - 如何在 ST(Twincat2)中使用 TRUE 初始化布尔数组?
- excel - 类模块,2 个带参数的选项