获取元素基本信息
获取文本内容
判断是否可见
判断是否可操作
获取元素的属性
获取元素CSS的值
清空内容
输入内容
单机
双击
1. 获取元素基本信息
from selenium import webdriverdriver = webdriver.Firefox(executable_path = "d:\\geckodriver")URL = "https://www.baidu.com"driver.get(URL)element = driver.find_element_by_xpath("//a[text() = '新闻']")#获取查找到的"新闻"链接元素的基本信息print(u"元素的标签名:",element.tag_name)print(u"元素的size:",element.size)
2. 获取页面元素的文本内容
driver = webdriver.Firefox(executable_path="d:\\geckodriver")driver.get("https://www.baidu.com")element = driver.find_element_by_xpath("//*[@class='mnav'][1]")text = element.textprint(text)#下面的验证是unittest框架的断言,如果没有可以先注释掉assertEqual(text,u"新闻")
3. 判断页面元素是否可见
driver = webdriver.Firefox(executable_path="d:\\geckodriver")driver.get("https://www.baidu.com")#定位其中一个元素element = driver.find_element_by_id("su")#判断是否可见,最终结果不是True就是Falseprint(element.is_displayed())
4.判断元素是否可操作
driver = webdriver.Firefox(executable_path="d:\\geckodriver")driver.get("https://www.baidu.com")#定位其中一个元素element = driver.find_element_by_id("su")#判断是否可操作,最终结果不是True就是False#如果HTML中元素添加disabled属性将处于补课操作状态print(element.is_enabled())
5.获取页面元素的属性
driver = webdriver.Firefox(executable_path="d:\\geckodriver")driver.get("https://www.baidu.com")#定位输入框元素element = driver.find_element_by_id("kw")#显示元素的name属性值,获取为wdprint(element.get_attribute("name"))#输入内容element.send_keys(u"python")#获取输入的内容 获取为pythonprint(element.get_attribute("value"))
6.获取页面元素的CSS属性值
driver = webdriver.Firefox(executable_path="d:\\geckodriver")driver.get("https://www.baidu.com")#定位其中一个元素element = driver.find_element_by_id("kw")#使用value_of_css_property()获取css属性值 高22px 宽500px print(u"搜索框的高度:",element.value_of_css_property("height"))print(u"搜索框的宽度:",element.value_of_css_property("width"))#获取字体,字体为arialziti = element.value_of_css_property("font-family")print(u"搜索框的字体是:",ziti)#unittest断言assertEqual(ziti,"arial")
7.清空输入的内容
driver = webdriver.Firefox(executable_path="d:\\geckodriver")URL = "https://www.baidu.com"driver.get(URL)#输入element = driver.find_element_by_id("kw")element.send_keys(u"python")#清空element.clear()
8.输入
driver = webdriver.Firefox(executable_path="d:\\geckodriver")URL = "https://www.baidu.com"driver.get(URL)#定位element = driver.find_element_by_id("kw")#清空原有内容element.clear()#输入新内容element.send_keys(u"python")
9.点击
driver = webdriver.Firefox(executable_path="d:\\geckodriver")URL = "https://www.baidu.com"driver.get(URL)#输入内容input = driver.find_element_by_id("kw")input.send_keys(u"输入python")#点击button = driver.find_element_by_id("su")button.click()
10.双击
请双击
driver = webdriver.Firefox(executable_path="d:\\geckodriver")url = "file:///D:/test.html"driver.get(url)#获取输入元素element = driver.find_element_by_id("inputBox")#导入需要的操作包from selenium.webdriver import ActionChains#开始模拟鼠标双击操作shuangji = ActionChains(driver)shuangji.double_click(element).perform()
说明:ActionChains是鼠标操作的包,比如双击、悬浮、拖拽等