selenium模拟鼠标键盘定位输入值的35例子(接上一篇第30例导入win32api库)

该博客介绍了如何结合selenium和win32api库进行模拟鼠标键盘操作,包括设置剪切板内容,以及在网页中进行交互。通过示例代码展示了在Python环境下设置剪切板文本的功能,并提供了测试用例。
摘要由CSDN通过智能技术生成

-- coding:utf-8 --

from selenium import webdriver
import unittest
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
import time
import win32clipboard as w
#自带一张键位表
import win32con

使用这个库才能定位右键弹出的菜单

import win32api
def setText(aString):#读取剪切板的函数
w.OpenClipboard()
w.EmptyClipboard()
w.SetClipboardData(win32con.CF_UNICODETEXT, aString)
w.CloseClipboard()

class GloryRoad(unittest.TestCase):
# 测试前的初始化工作
@classmethod
def setUpClass(cls):
# cls.driver=webdriver.Chrome()
options = webdriver.ChromeOptions()
options.add_argument(’–headless’)
cls.driver = webdriver.Chrome(options=options)
# 1.访问网站1,添加断言
def test_visiturl(self):
visiturl = ‘http://www.baidu.com
self.driver.get(visiturl)
# assert '百度0’in self.driver.page_source
# 断言
assert self.driver.title.find(‘百度’) >= 0, ‘页面标题不包含:百度’

# 2打开两个网站前进或者后退
def test_visitur2(self):
    visiturl = 'http://www.baidu.com'
    visitur2 = 'http://www.so.com'
    self.driver.get(visiturl)
    self.driver.get(visitur2)
    self.driver.back()
    self.driver.forward()

# 3刷新当前页面
def test_visitur3(self):
    visitur3 = 'http://www.sogou.com'
    self.driver.get(visitur3)
    self.driver.refresh()

# 4浏览器窗口最大化
def test_visitur4(self):
    visitur4 = 'http://www.sogou.com'
    self.driver.get(visitur4)
    self.driver.maximize_window()

# 5获取并设置当前窗口在屏幕上位置
def test_visitur5(self):
    visitur5 = 'http://www.sogou.com'
    self.driver.get(visitur5)
    # 获取当前窗口在屏幕上位置
    position = self.driver.get_window_position()
    print('横坐标:', position['x'])
    print('纵坐标:', position['y'])
    # 设置当前窗口在屏幕上位置
    self.driver.set_window_position(x=400, y=200)
    print(self.driver.get_window_position())
# 6获取浏览器窗口大小,返回字典类型数据
def test_visitur6(self):
    visitur6 = 'http://www.sogou.com'
    self.driver.get(visitur6)
    # 获取当前窗口在屏幕上位置
    size_Dict = self.driver.get_window_size()
    print('当前浏览器的宽:', size_Dict['width'])
    print('当前浏览器的高:', size_Dict['height'])
    # 设置浏览器窗口的大小
    self.driver.set_window_size(width=400, height=200,windowHandle='current')
    print(self.driver.get_window_size())
# 7获取页面的title属性值
def test_visitur7(self):
    visitur7 = 'http://www.baidu.com'
    self.driver.get(visitur7)
    current_web_title = self.driver.title
    print('当前网页的title属性值为:', current_web_title)
    #断言页面的title属性是否是“百度一下,你就知道”
    self.assertEqual(current_web_title,"百度一下,你就知道","页面title属性错误!")
#8获取页面HTML源代码
def test_visitur8(self):
    visitur8 = 'http://www.baidu.com'
    self.driver.get(visitur8)
    pagesource = self.driver.page_source
    # print('当前网页的源码为:', pagesource)
    #断言页面源码是否是包含“新闻”关键字,以此判断页面内容正确性
    self.assertTrue("新闻" in pagesource,"页面源码未找到'新闻'关键字")
#9获取当前页面的URL地址
def test_visitur9(self):
    visitur9 = 'http://www.baidu.com'
    self.driver.get(visitur9)
    currentpageurl = self.driver.current_url
    print('当前网页的URL为:', currentpageurl)
    #断言当前页面网址是否为https://www.baidu.com/
    self.assertEqual(currentpageurl, "https://www.baidu.com/", "当前网址非预期网址!")

# 10获取当前页面的元素基本信息
def test_visitur10(self):
    visitur10 = 'http://www.baidu.com'
    self.driver.get(visitur10)
    # 查找百度首页上的"新闻"链接元素
    newsElement = self.driver.find_element_by_xpath("//a[text()='新闻']")
    # 获取査找到的"新闻”链接元素的基本信息
    print("元素的标签名:", newsElement.tag_name)
    print("元素的 size:", newsElement.size)
# 11获取当前页面的元素文本内容
def test_visitur11(self):
    visitur11 = 'http://www.baidu.com'
    self.driver.get(visitur11)
    import time
    time.sleep(3)
    # 通过xpath定位方式找到id属性值为"ul"的div元素下的第一个链接元素
    aElement = self.driver.find_element_by_xpath("//*[@class='mnav'][1]")
    # 通过找到的链接元素对象的text属性获取到链接元素的文本内容
    a_text = aElement.text
    self.assertEqual(a_text, "新闻")
#12判断页面元素是否可见
def test_getWebElementIsDisplayed12(self):
    import os
    url12 = 'file:///' + os.path.abspath('A_12.html')
    # 访问自定义的HTML网页
    self.driver.get(url12)
    # 通过"div2"找到第二个div元素
    div2 = self.driver.find_element_by_id("div2")
    # 判断第二个div元素是否在页面上可见
    print(div2.is_displayed())
    # 单击第一个切换div按钮,将第二个div显示在页面上
    self.driver.find_element_by_id("button1").click()
    # 再次判断第二个div元素是否可见
    print(div2.is_displayed())
    # 通过id="div4"找到第四个div元素
    div4 = self.driver.find_element_by_id("div4")
    # 判断第四个div元素是否在页面上可见
    print(div4.is_displayed())
    # 单击第二个切换div按钮,将第四个div显示在页面上
    self.driver.find_element_by_id("button2").click()
    # 再次判断第四个div元素是否可见
    print(div4.is_displayed())
#13判断页面元素是否可操作
def test_getWebElementIsEnablec13(self):
    import os
    url13 = 'file:///' + os.path.abspath('A_13.html')
    # 访问自定义的HTML网页
    self.driver.get(url13)
    # 通过id找到第一个input元素
    input1 = self.driver.find_element_by_id("input1")
    # 判断第一个input元素是否可操作
    print(input1.is_enabled())
    # 通过id找到第二个:input元素
    input2 = self.driver.find_element_by_id("input2")
    # 判断第二个input元素是否可操作
    print(input2.is_enabled())
    # 通过id找到第三个input元素
    input3 = self.driver.find_element_by_id("input3")
    # 判断第三个input元素是否可操作
    print(input3.is_enabled())
#14获取页面元素的属性
def test_getWebElementAttribute14(self):
    url = "http://www.sogou.com"
    # 访问sogou首页
    self.driver.get(url)
    # 找到搜索输入框元素
    searchBox = self.driver.find_element_by_id("query")
    # 获取搜索输入框页面元素的name属性值
    print(searchBox.get_attribute("name"))
    # 向搜索输入框中输入"Selinum3"内容
    searchBox.send_keys("Selinum3")
    # 获取页面搜索框的value属性值(即搜索输入框的文字内容)
    print(searchBox.get_attribute("value"))
#15获取页面元素的CSS属性值
def test_getWebElementAttribute15(self):
    url = "http://www.baidu.com"
    # 访问百度首页
    self.driver.get(url)
    # 找到搜索输入框元素
    searchBox = self.driver.find_element_by_id("kw")
    # 使用页面元素对象的value_of_css_property()方法获取元素的CSS属性值
    print("搜索输入框的高度是:", searchBox.value_of_css_property("height"))
    print("搜索输入框的宽度是:", searchBox.value_of_css_property("width"))
    font = searchBox.value_of_css_property("font-family")
    print("搜索输入框的字体是:", font)
    # 断言搜索输入框的字体是否是arial字体
    self.assertEqual(font, "arial")
#16.清空输入框中的内容
def test_clearInputBoxText16(self):
    url = "http://www.baidu.com"
    # 访问百度网页
    self.driver.get(url)
    # 获取输入框页面对象
    input = self.driver.find_element_by_id("kw")
    input.send_keys("selenium")
    import time
    time.sleep(3)
    # 清除输人框中默认内容
    input.clear()
    # 等待3秒,主要看清空输入框内容后的效果
    time.sleep(3)
#17在输入框中输入指定内容
def test_sendTextToInputBoxText17(self):
    import os
    # url = "d:\\test.html"
    url = 'file:///' + os.path.abspath('a_17.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 获取输入框页面对象
    input = self.driver.find_element_by_id("text")
    # 清除输入框中默认内容
    input.clear()
    input.send_keys(u"我是输入的文本内容")
    # 导入time包
    import time
    # 等待3秒,主要看清空输入框内容后的效果
    time.sleep(3)
# 18单击按钮
def test_clickButton18(self):
    import os
    # url = "d:\\test.html"
    url = 'file:///' + os.path.abspath('A_18.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 获取按钮页面对象
    button = self.driver.find_element_by_id("button")
    # 模拟鼠标左键单击操作
    button.click()
    import time
    time.sleep(3)
#19双击某个元素
def test_doubleClick19(self):
    import os
    # url = "d:\\test.html"
    url = 'file:///' + os.path.abspath('A_19.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 获取页面输入元素
    inputBox = self.driver.find_element_by_id("inputBox")
    # 导入支持双击操作的模块
    from selenium.webdriver import ActionChains
    # 开始模拟鼠标双击操作
    action_chains = ActionChains(self.driver)
    action_chains.double_click(inputBox).perform()
    import time
    time.sleep(3)
    # 执行后双击input框,背景颜色将变为红色
# 20操作单选下拉列表
def test_printSelectText20(self):
    import os
    url = 'file:///' + os.path.abspath('A_20.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 使用name属性找到页面上name属性为"fruit”的下拉列表元素
    select = self.driver.find_element_by_name("fruit")
    all_options = select.find_elements_by_tag_name("option")
    for option in all_options:
        print("选项显示的文本:", option.text)
        print("选项值为:", option.get_attribute("value"))
        option.click()
        time.sleep(1)
    #20操作单选下拉列表(2)
    from selenium.webdriver.common.action_chains import ActionChains
    self.driver.get('http://www.baidu.com')
    setting = self.driver.find_element_by_link_text('设置')
    ActionChains(self.driver).move_to_element(setting).perform()  # 需要加.perform() 执行一下
    self.driver.find_element_by_link_text('高级搜索').click()
    self.driver.find_elements_by_class_name('c-input')
    time.sleep(2)
    # 导入Select包
    from selenium.webdriver.support.ui import Select
    ft = self.driver.find_element_by_name('ft')
    # 实例化一个select对象
    ft_list = Select(ft)
    print(type(ft), type(ft_list))
    ft_list.select_by_value('rtf')  # 通过value选择
    ft_list.select_by_index(1)  # 通过索引选择
    ft_list.select_by_visible_text('所有格式')  # 文本
#21断言单选列表选项值
def test_visitURL21(self):
    import os
    url='file:///'+os.path.abspath('A_20.html')
    self.driver.get(url)
    #导入select模块
    from selenium.webdriver.support.ui import Select
    select_element=Select(self.driver.find_element_by_xpath('/html/body/select'))
    #获取所有选项的页面元素对象
    actual_options=select_element.options
    except_optionslist=['桃子','西瓜','橘子','猕猴桃','山楂','荔枝']
    actual_options_list=list(map(lambda option:option.text,actual_options))
    self.assertListEqual(except_optionslist,actual_options_list)
#22操作多选的选择列表
def test_operateMultipleOptionDropList22(self):
    import os
    url = 'file:///' + os.path.abspath('A_22.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 导入Select模块
    from selenium.webdriver.support.ui import Select
    import time
    # 使用xpath定位方式获取select页面元素对象
    select_element = Select(self.driver.find_element_by_xpath("//select"))
    # 通过序号选择第一个元素
    select_element.select_by_index(0)
    # 通过选项的文本选择"山楂"选项
    select_element.select_by_visible_text("山楂")
    # 通过选项的value属性值选择value = "mihoutao"的选项
    select_element.select_by_value("mihoutao")
    # 打印所有的选中项文本
    for option in select_element.all_selected_options:
        print(option.text)
    # 取消所有已选中项
    select_element.deselect_all()
    time.sleep(2)
    print("------再次选中3个选项------")
    #用索引定位元素
    select_element.select_by_index(1)
    # 用文本定位元素
    select_element.select_by_visible_text("荔枝")
    #用value值定位元素
    select_element.select_by_value("juzi")
    # 通过选项文本取消已选中的文本为"荔枝"选项
    select_element.deselect_by_visible_text("荔枝")
    # 通过序号取消已选中的序号为1的选项
    select_element.deselect_by_index(1)
    # 通过选项的value属性值取消已选中的value = "juzi"的选项
    select_element.deselect_by_value("juzi")
# 23操作可以输入的下拉列表(输入的同时模拟按键)
def test_operateMultipleOptionDropList23(self):
    import os
    url = 'file:///' + os.path.abspath('A_23.html')
    self.driver.get(url)
    # 导入模拟键盘模块
    from selenium.webdriver.common.keys import Keys
    self.driver.find_element_by_id("select").clear()
    import time
    time.sleep(1)
    # 输入的同时按下箭头键
    self.driver.find_element_by_id("select").send_keys("c", Keys.ARROW_DOWN)
    self.driver.find_element_by_id("select").send_keys(Keys.ARROW_DOWN)
    self.driver.find_element_by_id("select").send_keys(Keys.ENTER)
    time.sleep(3)
#24操作单选框,is_selected判断元素是否被选中
def test_operateRadio24(self):
    import os
    url = 'file:///' + os.path.abspath('A_24.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 使用xpath定位获取value属性值为’berry’的input元素对象,也就是"草莓"选项
    berryRadio = self.driver.find_element_by_xpath("//input[@value = 'berry']")
    # 单击选择"草莓"选项
    berryRadio.click()
    # 断言"草莓”单选框被成功选中
    self.assertTrue(berryRadio.is_selected(), "草莓单选框未被选中!")
    if berryRadio.is_selected():
        # 如果"草莓"单选框被成功选中,重新选择n西瓜"选项
        watermelonRadio = self.driver.find_element_by_xpath("//input[@value ='watermelon']")
        watermelonRadio.click()
        # 选择"西瓜"选项以后,断言"草莓"选项处于未被选中状态
        self.assertFalse(berryRadio.is_selected())
    # 査找所有name属性值为"fruit"的单选框元素对象,并存放在radioList列表中
    radioList = self.driver.find_elements_by_xpath("//input[ @narae='fruit']")
    '''
    循环遍历radioList中的每个单选按钮,查找value属性值为"orange"的单选框,
    如果找到此单选框以后,发现未处于选中状态,则调用click方法选中该选项.'''
    for radio in radioList:
        if radio.get_attribute("value") == "orange":
            if not radio.is_selected():
                radio.click()
                self.assertEqual(radio.get_attribute("value"), "orange")
#25.操作复选框
def test_operateCheckBox25(self):
    import os
    url = 'file:///' + os.path.abspath('A_25.html')
    self.driver.get(url)
    # 使用xpath定位获取value属性值为'berry'的input元素对象,也就是"草莓"选项
    berryCheckBox = self.driver.find_element_by_xpath("//input[@value = 'berry' ]")
    # 单击选择"草莓"选项
    berryCheckBox.click()
    # 断言"草莓"复选框被成功选中
    self.assertTrue(berryCheckBox.is_selected(), u"草莓复选框未被选中!")
    if berryCheckBox.is_selected():
        # 如果"草莓"复选框被成功选中,再次单击取消选中
        berryCheckBox.click()
        # 断言"草莓"复选框处于未选中状态
        self.assertFalse(berryCheckBox.is_selected())
    # 査找所有name属性值为"fruit"的复选框元素对象,并存放在checkBoxList列表中
    checkBoxList = self.driver.find_elements_by_xpath("//input[@name = 'fruit']")
    # 遍历checkBoUst列表中的所有复选框元素,让全部复选框处于被选中状态
    for box in checkBoxList:
        if not box.is_selected():
            box.click()
# 26.断言页面源码中的关键字
def test_assertKeyWord26(self):
    url = "http://www.baidu.com"
    # 访问百度首页
    self.driver.get(url)
    self.driver.find_element_by_id("kw").send_keys(u"selenium")
    self.driver.find_element_by_id("su").click()
    import time
    time.sleep(4)
    # 通过断言页面是否存在某些关键字来确定页面按照预期加载
    assert "selenium" in self.driver.page_source, u"页面源码中不存在该关键字!"
#27对当前浏览器窗口截屏
def test_captureScreenInCurrentWindow27(self):
    url = "http://www.sogou.com"
    # 访问搜狗首页
    self.driver.get(url)
    try:
        '''
        调用get_screenshot_as_f ile(filename)方法,对浏览器当前打开页面
        进行截图,并保为C盘下的screenPicture.png文件
        '''
        result = self.driver.get_screenshot_as_file(r"C:\Users\Administrator\PycharmProjects\untitled58\screenPicture.png")
        print(result)
    except IOError as e:
        print(e)
#28.模拟键盘单个按键操作
def test_simulateASingleKeys28(self):
    from selenium.webdriver.common.keys import Keys
    url = "http://www.sogou.com"
    self.driver.get(url)
    query = self.driver.find_element_by_id("query")
    query.send_keys(Keys.F12)
    time.sleep(3)
    query.send_keys(Keys.F12)
    query.send_keys("selenium3")
    query.send_keys(Keys.ENTER)
    time.sleep(3)
#29.模拟组合按键操作
def test_simulationCombinationKeys29(self):
    url = "http://www.baidu.com"
    # 访问百度首页
    self.driver.get(url)
    # 将焦点切换到搜索输人框中
    input = self.driver.find_element_by_id("kw")
    input.click()
    input.send_keys(u"Selenium3")
    time.sleep(2)
    from selenium.webdriver import ActionChains
    from selenium.webdriver.common.keys import Keys
    ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('a'). \
        key_up(Keys.CONTROL).perform()
    time.sleep(2)
    ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('x'). \
        key_up(Keys.CONTROL).perform()
    self.driver.get(url)
    self.driver.find_element_by_id("kw").click()
    # 模拟Ctrl + V组合键,将从剪贴板中获取到的内容粘贴到搜索输入框中
    ActionChains(self.driver).key_down(Keys.CONTROL).send_keys('v'). \
        key_up(Keys.CONTROL).perform()
    # 单击"百度一下"搜索按钮
    self.driver.find_element_by_id("su").click()
    time.sleep(3)
#30.模拟鼠标右键,剪切板函数与类同级,是个公告函数和导入库都放在类前面

from selenium.webdriver import ActionChains

from selenium.webdriver.common.keys import Keys

import time

import win32clipboard as w

#自带一张键位表

import win32con

# 使用这个库才能定位右键弹出的菜单

import win32api

def setText(aString):#读取剪切板的函数

w.OpenClipboard()

w.EmptyClipboard()

w.SetClipboardData(win32con.CF_UNICODETEXT, aString)

w.CloseClipboard()

def test_rigthClickMouse(self):
    url = "http://www.sogou.com"
    # 访问搜狗首页
    self.driver.get(url)
    # 找到搜索输人框
    searchBox = self.driver.find_element_by_id("query")
    # 将焦点切换到搜索输入框
    searchBox.click()
    time.sleep(2)
    # 在搜索输入框上执行一个鼠标右键单击操作
    ActionChains(self.driver).context_click(searchBox).perform()
    # 将"gloryroad"数据设置到剪贴板中,相当于执行了复制操作
    setText(u'gloryroad')
    # # 发送一个粘贴命令,字符P指代粘贴操作
    # ActionChains(self.driver).send_keys('P').perform()
    win32api.keybd_event(40,win32con.KEYEVENTF_KEYUP,0)#移动到菜单
    win32api.keybd_event(80,win32con.KEYEVENTF_KEYUP,0)#然后按下p粘贴
    # 单击搜索按钮
    self.driver.find_element_by_id('stb').click()
    time.sleep(2)
#31模拟鼠标左键按下与释放
def test_simulationLeftClickMouseOfProcess31(self):
    import os
    url = 'file:///' + os.path.abspath('A_31.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    div = self.driver.find_element_by_id("div1")
    from selenium.webdriver import ActionChains
    import time
    # 在id属性值为"div1"的元素上执行按下鼠标左键,并保持
    ActionChains(self.driver).click_and_hold(div).perform()
    time.sleep(2)
    # 在id属性值为”div1”的元素上释放一直按下的鼠标左键
    ActionChains(self.driver).release(div).perform()
    time.sleep(2)
    ActionChains(self.driver).click_and_hold(div).perform()
    time.sleep(2)
    ActionChains(self.driver).release(div).perform()
#32保持鼠标悬停在某个元素上
def test_roverOnElement32(self):
    import os
    url = 'file:///' + os.path.abspath('A_32.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    # 找到页面上第一个链接元素
    link1 = self.driver.find_element_by_partial_link_text(u"鼠标指过来1")
    # 找到页面上第二个链接元素
    link2 = self.driver.find_element_by_partial_link_text(u"鼠标指过来2")
    # 找到页面上的p元素
    p = self.driver.find_element_by_xpath("//p")
    print(link1.text, link2.text)
    # 导入需要的Python包
    from selenium.webdriver import ActionChains
    import time
    # 将鼠标悬浮到第一个链接元素上
    ActionChains(self.driver).move_to_element(link1).perform()
    time.sleep(2)
    # 将鼠标从第一个链接元素移动到P元素上
    ActionChains(self.driver).move_to_element(p).perform()
    time.sleep(2)
    # 将鼠标悬浮到第二个链接元素上
    ActionChains(self.driver).move_to_element(link2).perform()
    time.sleep(2)
    # 将鼠标从第二个链接元素移动到P元素上
    ActionChains(self.driver).move_to_element(p).perform()
    time.sleep(2)
#33.判断页面元素是否存在
def isElementPresent(self, by, value):
    # 从 selenium.common.exceptions 模块导入 NoSuchElementException 异常类
    from selenium.common.exceptions import NoSuchElementException
    try:
        element = self.driver.find_element(by=by, value=value)
    except NoSuchElementException as e:
        # 打印异常信息
        print(e)
        # 发生了 NoSuchElementException异常,说明页面中未找到该元素,返回False
        return False
    else:
        # 没有发生异常,表示在页面中找到了该元素,返回True
        return True

def test_isElementPresent33(self):
    url = "http://www.sogou.com"
    # 访问sogou首页
    self.driver.get(url)
    # 判断页面元素id属性值为"query"的页面元素是否存在
    res = self.isElementPresent("id", "query")
    if res is True:
        print(u"所查找的元素存在于页面上!")
    else:
        print(u"页面中未找到所需要的页面元素!")
#34隐式等待implicitly_wait()
def test_iraplictWait34(self):
    # 导入异常类
    from selenium.common.exceptions import NoSuchElementException, TimeoutException
    # 导入堆栈类
    import traceback
    url = "http://www.sogou.com"
    # 访问sogou首页
    self.driver.get(url)
    # 通过driver对象impUcitly_wait()方法来设置隐式等待时间,最长等待10秒
    self.driver.implicitly_wait(10)
    try:
        # 査找sogou首页的搜索输人框页面元素
        searchBox = self.driver.find_element_by_id("query")
        # 在搜索输人框中输入"selenium3"
        searchBox.send_keys(u"selenium3")
        # 査找sogou首页搜索按钮页面元素
        click = self.driver.find_element_by_id("stb")
        # 单击搜索按钮
        click.click()
    except (NoSuchElementException, TimeoutException) as e:
        # 打印异常的堆栈信息
        traceback.print_exc()
#35显示等待WebDriverWait()
def test_explicitWait35(self):
    # 导入堆栈类
    import traceback
    # 导入By类
    from selenium.webdriver.common.by import By
    # 导入显式等待类
    from selenium.webdriver.support.ui import WebDriverWait
    # 导入期望场景类
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException, NoSuchElementException
    import os
    url = 'file:///' + os.path.abspath('A_35.html')
    # 访问自定义的HTML网页
    self.driver.get(url)
    try:
        wait = WebDriverWait(self.driver, 10, 0.2)
        wait.until(EC.title_is(u"你喜欢的水果"))
        print(u"网页标题是'你喜欢的水果'")
        # 等待10秒,直到要找的按钮出现
        element = WebDriverWait(self.driver, 10).until \
            (lambda x: x.find_element_by_xpath \
                ("//input[@value = 'Display alert box']"))
        element.click()
        # 等待alert框出现
        alert = wait.until(EC.alert_is_present())
        # 打印alert框体消息
        print(alert.text)
        # 确认警告信息
        alert.accept()
        # 获取id属性值为"peach"的页面元素
        peach = self.driver.find_element_by_id("peach")
        # 判断id属性值为"peach"的页面元素是否能被选中
        peachElement = wait.until(EC.element_to_be_selected(peach))
        print(u"下拉列表的选项'桃子'目前处于选中状态")
        # 判断复选框是否可见并且能被单击
        wait.until(EC.element_to_be_clickable((By.ID, 'check')))
        print("复选框可见并且能被单击")
    except TimeoutException as e:
        # 捕获 TimeoutException 异常
        print(traceback.print_exc())
    except NoSuchElementException as e:
        # 捕获 NoSuchElementException 异常
        print(traceback.print_exc())
    except Exception as e:
        # 捕获其他异常
        print(traceback.print_exc())


@classmethod
def tearDownClass(cls):
    cls.driver.quit()

if name == ‘main’:
unittest.main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值