I created this test.html
<!doctype html>
<html>
<head>
<title>test</title>
<script>
function inc() {
var counter = document.test.counter;
counter.value = parseInt(counter.value) + 1;
}
</script>
</head>
<body>
<form name="test">
<p>
<input type="text" value="0" name="counter" size="5">
<input type="button" id="increment" value="increment" onclick="inc();">
</p>
</form>
</body>
</html>
and test.py
import time
from os import path
from selenium import webdriver
driver = webdriver.Chrome()
driver.implicitly_wait(5)
driver.get(path.abspath("test.html"))
try:
n = 5
for i in range(n):
print("push %d / %d" % (i + 1, n))
driver.find_element_by_id("increment").click()
time.sleep(1)
except KeyboardInterrupt:
print("interrupted")
print("waiting")
time.sleep(5)
print("bye")
in a same directory.
When I run test.py
from a Command Prompt using a command python test.py
,
and I press Ctrl+C before "waiting"
is printed,
the Google Chrome window opened via Selenium is closed.
In my actual code, a loop is invoked from interactive Python console and runs indeterminate times. I want to fire keyboard interrupts to break from a loop without closing Google Chrome window for investigation and development.
What should I do to archive this?
My environment:
- Windows 7 Home Premium Service Pack 1 (64bit)
- Python 3.5.1 (64bit)
- Selenium 3.141.0
- urllib3 1.24.1
- ChromeDriver 2.45.615291 (ec3682e3c9061c10f26ea9e5cdcf3c53f3f74387)
- Google Chrome 72.0.3626.119 (Official Build) (64bit)
The system suggested a question Selenium: Quit Python script without closing browser, but this question didn't seem useful for me because:
raw_input()
seems waiting for user input. I want my program run without requiring manual input until I fire keyboard interrupts.- In my actual code, the time to sleep is long (about 10 minutes) instead of 1 second in the sample. The loop should be broken right after I fire keyboard interrupts, not after the sleeping is done.