Python selenium CTRL+C closes chromedriver

北城以北 提交于 2021-02-07 20:27:06

问题


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

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

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)

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.


回答1:


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.

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.

In your python script:

Chrome:

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)


来源:https://stackoverflow.com/questions/46135888/python-selenium-ctrlc-closes-chromedriver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!