SUM*_*GAN 10 python selenium multithreading webdriver python-multithreading
我正在开发一个需要位自动化和网络抓取的项目,我正在使用Selenium和BeautifulSoup (python2.7)。
我只想打开Web 浏览器的一个实例并登录到网站,保持该会话,我试图打开由线程独立控制的新选项卡,每个线程控制一个选项卡并执行自己的任务。我该怎么做?一个示例代码会很好。好吧,这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
如果需要,我愿意接受使用任何其他模块的建议
我的理解是 Selenium 驱动程序不是线程安全的。在 WebDriver 规范中,线程安全部分是空的……我认为这意味着他们根本没有解决这个话题。 https://www.w3.org/TR/2012/WD-webdriver-20120710/#thread-safety
因此,虽然您可以与多个线程共享驱动程序引用并从多个线程调用驱动程序,但不能保证驱动程序能够正确处理多个异步调用。
相反,您必须同步来自多个线程的调用以确保在下一个启动之前完成一个调用,或者您应该只有一个线程进行 Selenium API 调用......可能处理来自由多个其他线程填充的队列的命令。
另外,请参阅Selenium 是否可以在一个浏览器中使用多线程?
| 归档时间: |
|
| 查看次数: |
21787 次 |
| 最近记录: |