[英]After executing selenium python code google chrome closes automatically
此代碼運行沒有任何錯誤,但搜索 w3school 后會自動關閉谷歌瀏覽器
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
def google():
driver.get("https://www.google.com")
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys('w3school')
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)
google()
Selenium 總是在代碼運行完成后自動退出。 您可以添加 time.sleep() 以使其保持打開狀態。
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
driver = webdriver.Chrome()
def google():
driver.get("https://www.google.com")
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys('w3school')
driver.find_element_by_xpath('//* [@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)
time.sleep(10) #specify the seconds
google()
您必須在 function 之外打開一個瀏覽器實例,以便在執行 function 內的代碼后保持打開狀態
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome()
driver.get("https://www.google.com")
def google():
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input').send_keys('w3school')
driver.find_element_by_xpath('//*[@id="tsf"]/div[2]/div[1]/div[3]/center/input[1]').send_keys(Keys.ENTER)
google()
嘗試 webdriver 中提供的實驗選項,如下所示:
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(options=options, executable_path="path/to/executable")
警告:這確實會使 chrome 選項卡打開和分離,之后您必須手動關閉
因為“driver”變量是function中的局部變量,所以當function完成后,“driver”變量將被刪除,然后瀏覽器自動關閉。
=> 解決方案是您將“驅動程序”設置為程序中的全局變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.