如果我运行以下命令,就有一个时间窗口可以发送SIGINT,这样火狐的一个实例就会打开,而self.firefox就会没有定义。
try:
self.firefox = webdriver.Firefox(executable_path=os.getcwd()+"\\bin\\geckodriver.exe")
except:
pdb.set_trace()
if hasattr(self, 'firefox'):
self.firefox.quit()
raise这大概是因为中断发生在selenium启动浏览器和返回引用的点之间。
虽然次要的,当运行无头测试时,在错误的时间中断会让FF实例在没有引用的情况下打开。是否有一种方法可以识别和管理Selenium启动的Firefox实例,而不杀死用户在机器上运行的任何普通Firefox实例?
发布于 2019-01-13 15:20:14
我做了一些实验,最后提出了一个基于learner8269链接的解决方案。正如他在文章中提到的,在我的系统上,Windows 10 /当前的Geckodriver实例无法与普通Firefox进程区分开来。因此,我最后用一个try catch语句包装了对象创建&代码如下:
from subprocess import check_output
from selenium import webdriver
import re
tasklist = check_output(["tasklist", "/fi", "imagename eq firefox.exe"], shell=True).decode()
currentFFIDs = re.findall(r"firefox.exe\s+(\d+)", tasklist)
try:
firefox = webdriver.Firefox()
except:
tasklist = check_output(["tasklist", "/fi", "imagename eq firefox.exe"], shell=True).decode()
firefoxIds = set(re.findall(r"firefox.exe\s+(\d+)", tasklist)).difference(currentFFIDs)
taskkill = 'taskkill /f '+''.join(["/pid "+f+" " for f in firefoxIds]).strip()
check_output(taskkill.split(), shell=True)
print("\nFirefox was force closed\n", flush=True)这样做的目的是:
subprocess调用cmd中的tasklist命令并使用正则表达式提取进程ID列来完成的。tasklist &获取一组新的进程ID
tasklist进程之后创建的新火狐ID;这将终止任何无头火狐实例。发布于 2019-01-07 06:04:25
准确地说,已经有人回答了如何停止geckodriver实例:[https://stackoverflow.com/a/48003289/6892765][1]
现在回到当中断发生时如何使用它的问题。当您正在运行测试时,您必须使用一个测试引擎,例如pytest或类似的,它具有处理此类中断的能力。
专门用于pytest引擎:在conftest.py文件中实现pytest_exception_interact,当引发异常时调用该异常,该异常可能会被交互处理。
def pytest_exception_interact(node, call, report):
# Your code to perform geckodriver instance killinghttps://stackoverflow.com/questions/54068506
复制相似问题