簡體   English   中英

Python Selenium 用多線程打開多個瀏覽器

[英]Python Selenium Open Multiple Browsers With Multithreading

我正在嘗試使用 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()

我在那里傳遞的一個名為get_all_gdc_urls()的函數正在獲取 url 列表

就像現在一樣,它打開一個瀏覽器並開始在 url 列表中循環。 我需要添加什么才能打開更多瀏覽器?

非常感謝所有幫助。

我想我們可以使用隊列,希望這對你有用

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)

這只是一個公文包,允許您使用多線程打開多個 chrome 實例。 您需要對此代碼示例進行自己的修改。 希望它會有所幫助:)

def task1(url):
    chrome_options = Options()
    driver = webdriver.Chrome(options=chrome_options)
    driver.get(url)
    print('task completed')
url_list = ['http://www.google.com','http://www.spacex.com']
thread_list = []
for i in range(len(url_list)):
    thread_list.append(threading.Thread(target=task1,args=[url_list[i]]))
for i in range(len(thread_list)):
    thread_list[i].start()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM