python+selenium 3--實現Chrome判斷搜索結果並打開目標網址(斷言方式)

# coding=utf-8
import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
#driver.implicitly_wait(2)

driver.get("https://www.baidu.com")
driver.find_element_by_xpath("//*[@id='kw']").send_keys("selenium")
driver.find_element_by_xpath("//*[@id='su']").click()

time.sleep(3)
# 斷言方法判斷
ele_string = driver.find_element_by_xpath("//*[@id='1']/h3/a").text
if (ele_string == u"Selenium - Web Browser Automation"):
    print("結果和預期結果匹配!")
    #打開官網
    driver.find_element_by_xpath("//*[@id='1']/h3/a").click()
    print("測試成功,成功打開目標網址!")

#定義當前窗口句柄(百度)
baidu_handle = driver.current_window_handle
#獲取當前窗口句柄集合
handles = driver.window_handles
#print(handles)
# 獲取新窗口
new_handle = None
for handle in handles:
    if handle != baidu_handle:
        #捕獲新打開的窗口
        new_handle = handle
#print('switch to ', handle)
#新窗口打開搜索結果
driver.switch_to.window(new_handle)
time.sleep(10)

driver.quit()

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章