Python终端自动关闭求助:原正常Selenium脚本重启电脑后异常
Hey there, let's troubleshoot why your Selenium Chrome window is closing right away after restarting your PC. Based on your script and error snippet, here are the key fixes to try, starting with the most likely culprit:
1. Fix the Path Escape Error (Critical First Step)
Your ChromeDriver path uses single backslashes (\), which act as escape characters in Python. This is almost certainly causing a syntax error (matching the truncated error message you shared).
Update your driver initialization line to use one of these two safe formats:
- Raw string notation (prefix the path with
rto ignore escape sequences):browser = webdriver.Chrome(r'C:\Users\Jimmy\Downloads\chromedriver.exe') - Double backslashes (escape each backslash manually):
browser = webdriver.Chrome('C:\\Users\\Jimmy\\Downloads\\chromedriver.exe')
2. Check Chrome & ChromeDriver Version Compatibility
After restarting your PC, Chrome may have auto-updated in the background. ChromeDriver requires an exact major version match with your Chrome browser to work properly. A version mismatch will cause the driver to fail silently and close the window immediately.
- To check your Chrome version: Open Chrome → Go to
Settings > About Chrometo see your build number. - Replace your existing
chromedriver.exewith the version that matches your Chrome build.
3. Force the Window to Stay Open with ChromeOptions
Newer Selenium versions might close the browser window as soon as the driver process finishes, even with your input() line. Add these options to keep the window attached to your script:
from selenium import webdriver from selenium.webdriver.chrome.options import Options # Configure options to keep window open chrome_options = Options() chrome_options.add_experimental_option("detach", True) # Use your fixed path here browser = webdriver.Chrome(r'C:\Users\Jimmy\Downloads\chromedriver.exe', options=chrome_options) browser.get('http://www.supremenewyork.com/shop/all') # Add error handling for element lookup try: elem = browser.find_element_by_link_text('mustard') print("Successfully found the 'mustard' link!") except: print("Couldn't locate the 'mustard' link text on the page.") k = input("Press enter to exit")
4. Validate the Element Lookup
If the link text "mustard" doesn't exist on the page (or is loaded dynamically), the find_element_by_link_text call will throw an unhandled error that crashes the script and closes the window. The try-except block in the code above will catch this and let you debug without losing the window.
Start with fixing the path issue first—this is the most straightforward fix for the syntax error you're seeing. If that doesn't resolve it, move on to checking version compatibility.
内容的提问来源于stack exchange,提问作者user8589020




