python-selenium -- 彈出框處理


彈出框有兩種:頁面彈出框(可定位元素能操作)、Windows彈出框(不能直接定位)

一、頁面彈出框

  等待彈出框出現之后,定位彈出框,操作其中元素

  如: 

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
#點擊百度登錄按鈕
driver.find_element_by_xpath('//*[@id="u1"]//a[@name="tj_login"]').click()
 
#等待百度登錄彈出框中 要出現的元素可見
ele_id = "TANGRAM__PSP_10__footerULoginBtn"
param = (By.ID,ele_id)
#元素可見時,再進行后續操作
WebDriverWait(driver,10).until(EC.visibility_of_element_located(param))

driver.find_element_by_id(ele_id).click()
time.sleep(5)
driver.quit()

 

二、Windows彈出框

  使用 driver.switch_to.alert  切換到Windows彈出框

  Alert類提供了一系列操作方法:

  accept() 確定

  dismiss() 取消

  text() 獲取彈出框里面的內容

  send_keys(keysToSend) 輸入字符串

  如: 

#1:定位alert彈出框
#點擊頁面元素,觸發alert彈出框
driver.find_element_by_xpath('//*[@id="alert"]').click()
time.sleep(3)
#等待alert彈出框可見
WebDriverWait(driver,20).until(EC.alert_is_present())

#從html頁面切換到alert彈框
alert = driver.switch_to.alert
#獲取alert的文本內容
print(alert.text)
#接受--選擇“確定”
alert.accept()

#2:定位confirm彈出框
driver.find_element_by_xpath('//*[@id="confirm"]').click()
time.sleep(3)
WebDriverWait(driver,20).until(EC.alert_is_present())
alert =driver.switch_to.alert
print(alert.text)
# 接受--選擇“取消”
alert.dismiss()
 

#3:定位prompt彈出框
driver.find_element_by_id("prompt").click()
time.sleep(3)
WebDriverWait(driver,20).until(EC.alert_is_present())
alert =driver.switch_to.alert
alert.send_keys("jaja")
time.sleep(5)
print(alert.text)
# alert.dismiss()
alert.accept()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM