selenium Python定位元素和相关事件

场景

经过使用selenium python的API可以很好的定位html中的元素,并指挥鼠标进行点击。html

定位元素

find_element_by_*方法

  • find_element_by_id(id_) : html标签中的id肯定标签
  • find_element_by_link_text(link_text):html标签中的文本内容肯定标签
  • find_element_by_partial_link_text(link_text):html标签中的文本部份内容肯定标签
  • find_element_by_xpath(xpath):使用xpath语法来肯定html标签

这里前3种方式都比较好理解,相对陌生的就是Xpath语法,xpath例子:node

# -*- coding: utf-8 -*-
from selenium import webdriver
# 包含ABC字符串的html标签,而后,再向上找两层父节点
mouse = driver.find_element_by_xpath("//*[contains(text(),'ABC')]/../..")

这里若是是中文,须要在Python源代码最上面一行设置:# -*- coding: utf-8 -*-.python

点击事件

# click方法点击html标签
driver.find_element_by_id("Button1").click()

上面的这个方法能够会没有效果,由于有的页面设计成,必须须要鼠标先悬浮在html标签元素上,而后,进行点击才是有效点击,这样的事件,应使用以下方式处理:git

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 使用xpath语法找到元素
mouse = driver.find_element_by_xpath("//*[contains(text(),'ABC')]/../..")
# move_to_element方法让鼠标实现悬浮事件
# click方法让鼠标进行点击事件
# perform方法统一完成上述2个事件
ActionChains(driver).move_to_element(mouse).click(mouse).perform()

这里主要就是ActionChains的使用。github

输入事件

# 找到html标签,使用send_keys方法键盘输入hello
driver.find_element_by_id("uid").send_keys("hello")

参考

相关文章
相关标签/搜索