Python selenium CTRL+C 关闭 chromedriver [英] Python selenium CTRL+C closes chromedriver

查看:90
本文介绍了Python selenium CTRL+C 关闭 chromedriver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不导致 chromedriver 关闭的情况下捕获 CTRL+C(键盘中断).当我通过 cmd 运行我的 script.py 时,它会关闭 chromedriver.

How can I catch CTRL+C (a KeyboardInterrupt) without causing the chromedriver to close. It closes the chromedriver when I run my script.py through cmd.

driver = webdriver.Chrome()
try:
    while True:
        #do stuff with chromedriver
except KeyboardInterrupt:
    print "User pressed CTRL + C"
    #do other stuff with chromedriver

它确实在我的脚本中捕获了 KeyboardInterrupt,因此我的脚本继续运行,但 chromedriver 也得到它并自行关闭.

It does catch the KeyboardInterrupt in my script, thus my script continues but the chromedriver also gets it and close itself.

编辑 1:
解决方案此处在您通过 CMD 运行脚本时或当你用 Pyinstaller 冻结脚本并运行它(IOError: [Errno 4] Interrupted function call)

EDIT 1:
The solution here doesn't work when you run the script through CMD or when you freeze the script with Pyinstaller and run it (IOError: [Errno 4] Interrupted function call)

编辑 2:
我还尝试让脚本忽略 Errno 4(使用 tryexcept Exception)但仍然有相同的结果(chromedriver 关闭)所以简而言之,这个解决方案根本没有帮助.

EDIT 2:
I also tried by making the script ignore the Errno 4 (using try and except Exception) but still has the same result (chromedriver closes) so in short, this solution does not help at all.

推荐答案

考虑使用 webdriver.Remote 风格.此选项不会在解释器中生成本地版本的 webdriver,这将使您免于 SIGINT 的麻烦.

Consider using the webdriver.Remote flavor. This option does not spawn a local version of the webdriver inside the interpreter, which should free you from the SIGINT hassle.

在另一个 shell 中启动 webdriver -(Chrome 的 chromedriver,Firefox 的 geckodriver 等)记下监听端口.我将在这里使用默认值:chromedriver 为 9515,geckodriver 为 4444.

Initiate the webdriver in another shell - (chromedriver for Chrome, geckodriver for Firefox, etc.) Take note of the listening port. I will use the defaults here: 9515 for chromedriver and 4444 for geckodriver.

在你的 python 脚本中:

In your python script:

铬:

driver=webdriver.Remote("http://127.0.0.1:9515",desired_capabilities=webdriver.DesiredCapabilities.CHROME)

Firerox:

driver=webdriver.Remote("http://127.0.0.1:4444",desired_capabilities=webdriver.DesiredCapabilities.FIREFOX)

这篇关于Python selenium CTRL+C 关闭 chromedriver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆