我有一个循环运行的Python Selenium脚本,它每隔100次迭代退出浏览器......
def init_driver():
ffprofile = webdriver.FirefoxProfile("my_profile");
ffprofile.add_extension(extension="myaddon.xpi")
return driver
driver = init_driver()
for i, item, in enumerate(item_list):
check_item(item)
print ( "" )
if i == 0:
print ( "Ignoring First Item" )
elif i % 100 == 0:
driver.quit()
driver = init_driver()
在重新启动驱动程序期间,它随机崩溃并出现错误...
Traceback (most recent call last):
File "C:\scripts\main.py", line 118, in <module>
driver = init_driver()
File "C:\scripts\main.py", line 98, in init_driver
driver = webdriver.Firefox(firefox_profile=ffprofile)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 78, in __init__
self.binary, timeout)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\extension_connection.py", line 49, in __init__
self.profile.add_extension()
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\firefox_profile.py", line 91, in add_extension
self._install_extension(extension)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\site-packages\selenium\webdriver\firefox\firefox_profile.py", line 287, in _install_extension
shutil.rmtree(tmpdir)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 488, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 383, in _rmtree_unsafe
onerror(os.unlink, fullname, sys.exc_info())
File "C:\Users\john\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 381, in _rmtree_unsafe
os.unlink(fullname)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\john\\AppData\\Local\\Temp\\tmpoaizz71l.webdriver.xpi\\platform\\WINNT_x86-msvc\\components\\imehandler.dll'
有时它可以经历数千次迭代而不会崩溃,有时则会在100次之后发生。
有人知道发生了什么事吗?
答案 0 :(得分:2)
可能这种情况发生在临时配置文件删除时,由于竞争条件 - 共享libtary仍然访问目录。 Firefox和Selenium是非常异步的,所以有时候只是在流程的各个阶段发生,您可以查看类型的问题等待加载元素&#39;和我一样。
我想你有两个实际的选择来处理这个问题:如果这种情况发生/很少/只是,只需在driver_init
附近的代码中添加一个try-except-wait-repeat块。这很丑陋,但有时它是努力结果的唯一合理方式。
或者,您可以切换平台:)在像Linux这样的系统中,打开的文件通常不会阻止它们被删除。
答案 1 :(得分:2)
另一种解决方法以及@user3159253's answer在driver.quit()
和driver = init_driver()
之间添加了较短的等待时间。如果打开新浏览器不是时间关键,可能需要等待0.5或1.0秒并增加/减少,直到发生错误。
如果实验太多,请按照他/她的回答中的建议将其与try...except
块结合使用,并在driver.quit()
之前启动计时器并检查异常时间过去了多长时间发生。