首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在没有对象引用的情况下杀死webdriver实例

在没有对象引用的情况下杀死webdriver实例
EN

Stack Overflow用户
提问于 2019-01-07 04:19:48
回答 2查看 169关注 0票数 0

如果我运行以下命令,就有一个时间窗口可以发送SIGINT,这样火狐的一个实例就会打开,而self.firefox就会没有定义。

代码语言:javascript
运行
复制
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实例?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-13 15:20:14

我做了一些实验,最后提出了一个基于learner8269链接的解决方案。正如他在文章中提到的,在我的系统上,Windows 10 /当前的Geckodriver实例无法与普通Firefox进程区分开来。因此,我最后用一个try catch语句包装了对象创建&代码如下:

代码语言:javascript
运行
复制
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)

这样做的目的是:

  • 获取运行Firefox实例的当前进程ID
  • 这是通过subprocess调用cmd中的tasklist命令并使用正则表达式提取进程ID列来完成的。
  • 尝试并启动webdriver实例;如果成功,则运行tasklist &获取一组新的进程ID
    • 这现在可能包括Selenium启动的ID。

  • 将新ID转换为集合&从其中移除所有原始ID
  • 调用"taskkill“,并提供在第一个tasklist进程之后创建的新火狐ID;这将终止任何无头火狐实例。
票数 0
EN

Stack Overflow用户

发布于 2019-01-07 06:04:25

准确地说,已经有人回答了如何停止geckodriver实例:[https://stackoverflow.com/a/48003289/6892765][1]

现在回到当中断发生时如何使用它的问题。当您正在运行测试时,您必须使用一个测试引擎,例如pytest或类似的,它具有处理此类中断的能力。

专门用于pytest引擎:在conftest.py文件中实现pytest_exception_interact,当引发异常时调用该异常,该异常可能会被交互处理。

代码语言:javascript
运行
复制
def pytest_exception_interact(node, call, report):
    # Your code to perform geckodriver instance killing
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54068506

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档