我正在一个需要位自动化和Web剪贴的项目,我正在使用 Selenium 和 BeautifulSoup(python2.7)。
我只想打开网页浏览器的一个实例并登录到网站,保持该 session ,我试图打开将由线程独立控制的新选项卡,每个线程控制一个选项卡并执行它们自己的任务。我该怎么办?一个示例代码会很好。好吧,这是我的代码:
def threadFunc(driver, tabId):
if tabId == 1:
#open a new tab and do something in it
elif tabId == 2:
#open another new tab with some different link and perform some task
.... #other cases
class tabThreads(threading.Thread):
def __init__(self, driver, tabId):
threading.Thread.__init__(self)
self.tabID = tabId
self.driver = driver
def run(self):
print "Executing tab ", self.tabID
threadFunc(self.driver, self.tabID)
def func():
# Created a main window
driver = webdriver.Firefox()
driver.get("...someLink...")
# This is the part where i am stuck, whether to create threads and send
# them the same web-driver to stick with the current session by using the
# javascript call "window.open('')" or use a separate for each tab to
# operate on individual pages, but that will open a new browser instance
# everytime a driver is created
thread1 = tabThreads(driver, 1)
thread2 = tabThreads(driver, 2)
...... #other threads
如果需要,我欢迎使用其他模块的建议
最佳答案
我的理解是Selenium驱动程序不是线程安全的。在WebDriver规范中,“线程安全性”部分为空...我要表示它们根本没有解决该主题。 https://www.w3.org/TR/2012/WD-webdriver-20120710/#thread-safety
因此,尽管可以与多个线程共享驱动程序引用并从多个线程对该驱动程序进行调用,但不能保证该驱动程序将能够正确处理多个异步调用。
相反,您必须同步多个线程的调用以确保一个线程在下一个线程开始之前完成,或者您应该只有一个线程进行Selenium API调用...可能处理来自多个其他线程填充的队列中的命令。
另请参阅Can Selenium use multi threading in one browser?