Selenium中的多线程/多处理

2024-10-03 19:27:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个python脚本,从文本文件中提取URL,并从元素中打印出href。然而,我在这里的目标是使它更快,能够在更大范围内使用多处理或多线程处理

在工作流中,每个浏览器进程将从当前url获取href,并在同一浏览器距离中从que加载下一个链接(假设有5个)。当然,每个链接应该被刮1次

示例输入文件HNlinks.txt

https://news.ycombinator.com/user?id=ingve
https://news.ycombinator.com/user?id=dehrmann
https://news.ycombinator.com/user?id=thanhhaimai
https://news.ycombinator.com/user?id=rbanffy
https://news.ycombinator.com/user?id=raidicy
https://news.ycombinator.com/user?id=svenfaw
https://news.ycombinator.com/user?id=ricardomcgowan

代码:

from selenium import webdriver

driver = webdriver.Chrome()
input1 = open("HNlinks.txt", "r")
urls1 = input1.readlines()

for url in urls1:
    driver.get(url)

    links=driver.find_elements_by_class_name('athing')
    for link in links:
        print(link.find_element_by_css_selector('a').get_attribute("href"))

Tags: httpstxtcomidurl链接driver浏览器
1条回答
网友
1楼 · 发布于 2024-10-03 19:27:34

使用多处理*

注意:我没有在本地测试这个答案。 请尝试并给出反馈:

from multiprocessing import Pool
from selenium import webdriver

input1 = open("HNlinks.txt", "r")
urls1 = input1.readlines()

def load_url(url):
    driver = webdriver.Chrome()
    driver.get(url)
    links=driver.find_elements_by_class_name('athing')
    for link in links:
        print(link.find_element_by_css_selector('a').get_attribute("href"))

if __name__ == "__main__":
    # how many concurrent processes do you want to span? this is also limited by 
    the number of cores that your computer has.
    processes = len(urls1)
    p = Pool(processes ) 
    p.map(load_url, urls1)
    p.close()
    p.join()

相关问题 更多 >