首页 > 解决方案 > Python Selenium 使用多线程打开多个浏览器

问题描述

我正在尝试使用 Selenium 和 Chrome 循环浏览大约 20000 个 URL 的列表。在一个浏览器中执行此操作当然需要很长时间。所以我试图在这个测试用例中将它设置为在 5 个浏览器中打开。我看了一些教程,但我仍然在努力弄清楚。到目前为止,这是我的代码:

def check_all_urls(urls):
    options = Options()
    options.headless = False
    driver = webdriver.Chrome(options=options)

    for url in urls:
        my_urls = ('\n'.join(''.join(el) for el in url))
        driver.get(my_urls)


number_of_threads = 5

threads = []

for number in range(number_of_threads):
    t = threading.Thread(target=check_all_urls(get_all_gdc_urls()), args=(number,))
    t.start()

url 列表被我传入的一个名为get_all_gdc_urls()

就像现在一样,它打开一个浏览器并开始循环浏览 url 列表。我需要添加什么才能打开更多浏览器?

非常感谢所有帮助。

标签: pythonmultithreadingseleniumselenium-webdriver

解决方案


我想我们可以使用队列,我希望这对你有用

from threading import Thread
from Queue import Queue

concurrent = 5
s=1
def doWork():
    while True:
        url = q.get()
        urlstatus = crawl(url)
        q.task_done()

def crawl(myurl):
    options = Options()
    options.headless = False
    driver = webdriver.Chrome(options=options)
    driver.get(my_url)
    driver.close()

q = Queue(concurrent * 2)
for i in range(concurrent):
    t = Thread(target=doWork)
    t.daemon = True
    t.start()
try:
    with open("urls.txt") as infile:
        for line in infile:
            lin="https://"+line
            q.put(lin.strip())
    q.join()
except KeyboardInterrupt:
    sys.exit(1)

推荐阅读