场景
通过使用selenium python的API能够很好的定位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例子:
# -*- coding: utf-8 -*-
from selenium import webdriver
# 包含ABC字符串的html标签,然后,再向上找两层父节点
mouse = driver.find_element_by_xpath("//*[contains(text(),'ABC')]/../..")
这里如果是中文,需要在Python源代码最上面一行设置:# -*- coding: utf-8 -*-.
点击事件
# click方法点击html标签
driver.find_element_by_id("Button1").click()
上面的这个方法可以会没有效果,因为有的页面设计成,必须需要鼠标先悬浮在html标签元素上,然后,进行点击才是有效点击,这样的事件,应使用如下方式处理:
# -*- 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的使用。
输入事件
# 找到html标签,使用send_keys方法键盘输入hello
driver.find_element_by_id("uid").send_keys("hello")
本文详细介绍如何使用Selenium Python库进行网页自动化测试,包括定位HTML元素、触发鼠标点击及键盘输入事件。涵盖find_element_by_*系列方法的使用,如通过ID、链接文本或XPath定位元素,以及使用ActionChains模拟鼠标悬停并点击复杂交互元素。
789

被折叠的 条评论
为什么被折叠?



