使用 url 范围时如何在 Selenium Python 中添加多线程?
所以我的想法是,如果我添加一些可以将 url 范围拆分为 5 个的内容,然后为 5 个 chromedriver 实例中的每一个实例提供自己的 url 范围拆分来处理它,将使抓取速度更快。这是我最大的问题。但如果每个 chromedriver 都有自己的 csv 文件,也许会更好,或者我需要添加一些东西来将所有抓取内容集中在一个文件中?我在这里真的很茫然,但我已经在提高我的技能水平了。我永远感激您至少在如何使多线程工作方面提供的任何具体帮助。谢谢你!
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import csv
path_to_file = "test1.csv"
csvFile = open(path_to_file, 'a', encoding="utf-8", newline='')
csvWriter = csv.writer(csvFile)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
header_added = False
time.sleep(3)
for i in range(1,153512):
print(f"https://www.ancestry.com/discoveryui-content/view/{i}:61965")
driver.get(f"https://www.ancestry.com/discoveryui-content/view/{i}:61965")
try:
Name = driver.find_element(By.XPATH,"//table[@id='recordServiceData']//tr[contains(.,'Name:')]").text.replace("Name:", "")
except:
Name =''
csvWriter.writerow([i, Name])
print(Name)
So my thoughts are that if I would add something that can split the url-range into 5 and then give each of 5 chromedriver instances their own split of the url-range to handle it would make scraping much faster. And thats my biggest question. But maybe then its better if each chromedriver had their own csv file, or I would need to add something that pools all the scraping in one file? Im really at a loss here and I'm already pushing my skill level. I am eternally grateful for any concrete help on at least how to get multithreading working. Thank you!
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import csv
path_to_file = "test1.csv"
csvFile = open(path_to_file, 'a', encoding="utf-8", newline='')
csvWriter = csv.writer(csvFile)
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
header_added = False
time.sleep(3)
for i in range(1,153512):
print(f"https://www.ancestry.com/discoveryui-content/view/{i}:61965")
driver.get(f"https://www.ancestry.com/discoveryui-content/view/{i}:61965")
try:
Name = driver.find_element(By.XPATH,"//table[@id='recordServiceData']//tr[contains(.,'Name:')]").text.replace("Name:", "")
except:
Name =''
csvWriter.writerow([i, Name])
print(Name)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
try this: