Python3 Selenium自动化web测试 ==> 第七节 WebDriver高级应用 -- 浮动框中,单击选择某个关键字选项...

本文介绍了一个使用Python和Selenium WebDriver进行高级操作的例子,包括如何利用键盘事件选择下拉选项及通过模糊匹配选择搜索建议。

学习目的:


 

  了解WebDriver的高级应用

 

正式步骤:


 

测试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()

 

转载于:https://www.cnblogs.com/wuzhiming/p/9164762.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值