我正在从事一个需要位自动化和网络剪接的项目,我正在使用 selenium and 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
i AM 开放的建议使用任何其他模块,如果需要的话
我的理解是硒驱动程序不是线程安全。在WebDriver规范中,线程安全部分是空的……我认为他们根本没有解决该主题。https://www.w3.org/tr/2012/wd-webdriver-20120710/#thread-safety
因此,虽然您可以与多个线程共享驱动程序参考并通过多个线程进行呼叫,但不能保证驱动程序能够正确处理多个异步调用。
相反,您必须同步来自多个线程的调用,以确保一个在下次启动之前完成,或者您应该只有一个线程制作硒api调用...可能会从排队中处理命令,该命令是由多个其他线程填充的队列。
另外,请参见硒可以在一个浏览器中使用多线程吗?
i您使用脚本自动提交表格(简单地说做求出和发布请求),我建议您查看请求。您可以轻松地从浏览器(Firefox和Chrome上的开发人员窗格中的 network tab)中轻松捕获发布请求,并提交它们。类似:
session = requests.session()
response = session.get('https://stackoverflow.com/')
soup = BeautifulSoup(response.text)
,甚至发布数据,例如:
postdata = {'username':'John','password':password}
response=session.post('example.com',data=postdata,allow_redirects=True)
它可以轻松地穿线,比使用硒更快多次,唯一的问题是没有JavaScript或形式支持,因此您需要以老式的方式进行操作。
编辑:还要查看ThreadPoolExecutor