test.py
from selenium import webdriver driver = webdriver.Chrome() driver.get("http://www.baidu.com") # 搜索輸入框 search_input = driver.find_element_by_id("kw") # 搜索selenium search_input.send_keys("selenium") # 搜索按鈕 search_button = driver.find_element_by_id("su") # 點擊搜索按鈕 search_button.click()
瀏覽器窗口不會自動關閉
elementLocator.py
from selenium import webdriver import time class elementLocator(): def __init__(self): self.driver= webdriver.Chrome() self.driver.get("http://www.baidu.com") self.driver.maximize_window() #xpath定位 def elementLocator_xpath(self): #定位到登錄按鈕 login_button = self.driver.find_element_by_xpath("//a[@id='s-top-loginbtn']") #相對定位 #login_button = self.driver.find_element_by_xpath("/html/body/div/div/div[4]/a") #絕對定位(不建議) #點擊登錄按鈕 login_button.click() elementLocator().elementLocator_xpath()
結果:瀏覽器自動關閉
原因:在函數內執行的瀏覽器操作,在函數執行完畢之后,程序內所有的步驟都結束了,關於這段程序的進程也就結束了,瀏覽器包含在內;如果將瀏覽器全局后,打開瀏覽器不在函數內部,函數里面的程序執行完是不會關閉瀏覽器的。
解決方法:
設置option.add_experimental_option("detach", True)不自動關閉瀏覽器
from selenium import webdriver import time class elementLocator(): def __init__(self): # 加啟動配置 option = webdriver.ChromeOptions() # 關閉“chrome正受到自動測試軟件的控制” # V75以及以下版本 # option.add_argument('disable-infobars') # V76以及以上版本 option.add_experimental_option('useAutomationExtension', False) option.add_experimental_option('excludeSwitches', ['enable-automation']) # 不自動關閉瀏覽器 option.add_experimental_option("detach", True) self.driver= webdriver.Chrome(chrome_options=option) self.driver.get("http://www.baidu.com") self.driver.maximize_window() #xpath定位 def elementLocator_xpath(self): #定位到登錄按鈕 login_button = self.driver.find_element_by_xpath("//a[@id='s-top-loginbtn']") #相對定位 #login_button = self.driver.find_element_by_xpath("/html/body/div/div/div[4]/a") #絕對定位(不建議) #點擊登錄按鈕 login_button.click() time.sleep(4) self.driver.close() elementLocator().elementLocator_xpath()
參考連接:https://blog.csdn.net/qq_43422918/article/details/97394705
