首页 > 解决方案 > 打开多线程后与 selenium 实例交互

问题描述

在产生 5 个线程后,我试图同时与不同的 selenium 实例进行交互。

这是我的代码:

from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
import os
import threading

path = r"path"
torexe = os.popen(r"path")
profile = FirefoxProfile(r"path")
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.socks', '127.0.0.1')
profile.set_preference('network.proxy.socks_port', 9050)
profile.set_preference("network.proxy.socks_remote_dns", False)
profile.update_preferences()
options = webdriver.FirefoxOptions()
options.add_argument('--incognito')
options.add_argument('--headless')
#driver = webdriver.Firefox(firefox_profile=profile,options=options,executable_path=path)

def open_thread():
    driver = webdriver.Firefox(options=options, executable_path=path)
    driver.get("https://time.is/")  # replace here by driver.get(test_url)
    time = driver.find_element_by_xpath("//*[@id='clock0_bg']").text
    print(time)
    driver.quit()

N = 3   # Number of browsers to spawn
thread_list = list()

while True:
# Start test
    for i in range(N):
        t = threading.Thread(name='Test {}'.format(i), target=open_thread())
        t.start()
        #time.sleep(1)
        print(t.name + ' started!')
        thread_list.append(t)

    # Wait for all threads to complete
    #for thread in thread_list:

现在它正在打开一个实例,然后打印时间并关闭浏览器。但我想先打开 3 个实例,然后打印 3 个时间,然后关闭浏览器,然后重新开始。

我的直觉是找出时间并在最后一个 for 循环中打印出来。但是对驱动程序的引用不起作用:

def open_thread():
    driver = webdriver.Firefox(options=options, executable_path=path)
    driver.get("https://time.is/")  # replace here by driver.get(test_url)

N = 3   # Number of browsers to spawn
thread_list = list()

while True:
# Start test
    for i in range(N):
        t = threading.Thread(name='Test {}'.format(i), target=open_thread())
        t.start()
        #time.sleep(1)
        print(t.name + ' started!')
        thread_list.append(t)

    # Wait for all threads to complete
    for thread in thread_list: 
        time = driver.find_element_by_xpath("//*[@id='clock0_bg']").text
        print(time)
        driver.quit()

标签: pythonseleniumselenium-webdriverweb-scrapingpython-multithreading

解决方案


推荐阅读