python - 如何停止出现以下错误?从 python 打开 chrome 浏览器时
问题描述
注意:代码会打开 chrome 浏览器,但也会出现上述错误。
from selenium import webdriver
main_url = 'https://www.linkedin.com' # URL A
tab_url = 'https://www.google.com' # URL B
chromedriver = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'
# Open main window with URL A
browser= webdriver.Chrome(chromedriver)
browser.get(main_url)
尝试运行脚本时出现以下错误。
Error: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0
解决方案
我更喜欢使用 webdriver_manager 来设置 execution_path 变量,并在您运行脚本时自动下载驱动程序。
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
main_url = 'https://www.linkedin.com' # URL A
tab_url = 'https://www.google.com' # URL B
# Open main window with URL A
browser= webdriver.Chrome(ChromeDriverManager().install())
browser.get(main_url)
如果您打算在 2 个单独的选项卡中打开这两个网址,请使用以下内容。
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
main_url = 'https://www.linkedin.com' # URL A
tab_url = 'https://www.google.com' # URL B
# Open main window with URL A
browser= webdriver.Chrome(ChromeDriverManager().install())
browser.get(main_url)
#print the current url
print(driver.current_url)
# open tab_url in new window
driver.execute_script("window.open(tab_url)")
# switch to the new window
driver.switch_to.window(driver.window_handles[1])
# check if the url is equals to tab_url
print(driver.current_url)
if driver.current_url == tab_url:
print(driver.current_url + " - Passed.")
driver.close()
# close the window
driver.close()