Python3 Selenium自動化web測試 ==> 第七節 WebDriver高級應用 -- 浮動框中,單擊選擇某個關鍵字選項

學習目的:


 

  瞭解WebDriver的高級應用web

 

正式步驟:


 

測試Python3代碼瀏覽器

# -*-  coding:utf-8 -*-
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
import unittest
import time
import traceback


class WebdriverAPI(unittest.TestCase):
    def setUp(self):
        # 每一個用例都執行,在單個用例運行前執行
        #打開瀏覽器
        self.driver = webdriver.Chrome()

    def tearDown(self):
        #每一個用例都執行,在單個用例運行後執行
        #退出瀏覽器
        self.driver.quit()

    def test_selectAjaxOption(self):
        url = "https://www.baidu.com/"
        #使用向下鍵選擇
        self.driver.get(url)
        searchBox = self.driver.find_element_by_id('kw')
        searchBox.send_keys('世界盃')
        time.sleep(1)
        for i in range(3):
            searchBox.send_keys(Keys.DOWN)
            time.sleep(0.5)
        searchBox.send_keys(Keys.ENTER)
        time.sleep(2)

        #經過模糊匹配查詢
        self.driver.get(url)
        try:
            searchBox2 = self.driver.find_element_by_id('kw')
            searchBox2.send_keys('世界盃')
            time.sleep(2)
            #模糊匹配內容會跟當前熱詞有所變化
            target_option = self.driver.find_element_by_xpath("//ul/li[contains(.,'時間')]")
            target_option.click()
            time.sleep(2)
        except WebDriverException:
            print(traceback.print_exc())
if __name__ == '__main__':
    unittest.main()
相關文章
相關標籤/搜索