python_selenium元素定位_xpath(2)

  selenium自动化脚本最基础的就是元素定位和元素操作,下面就以百度为例介绍最常见的xpath定位方式

基本定位方式:

以百度的搜索框为例

from selenium import webdriver
import time
driver  = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
time.sleep(2)
# 1、绝对路径
# driver.find_element_by_xpath("/html/body/div/div/div/div/div/form/span/input").send_keys("龙猫")
# 2、相对路径
# driver.find_element_by_xpath("//form/span/input").send_keys("龙猫")
# 3、通过元素索引定位
# driver.find_element_by_xpath("//div/div[3]/a[3]").click()
# 4、使用元素属性定位
 # 4.1 单属性
# driver.find_element_by_xpath("//input[@maxlength = ‘255‘]").send_keys("小狗")
 # 4.2 多属性and
# driver.find_element_by_xpath("//input[@maxlength=‘255‘ and @autocomplete=‘off‘]").send_keys("小狗")
 # 4.3 多属性or
# driver.find_element_by_xpath("//input[@maxlength=‘259‘ or @autocomplete=‘off‘]").send_keys("小狗")
# 5、模糊匹配
 # 5.1 以什么开头starts-with()
# driver.find_element_by_xpath("//a[starts-with(@name,‘tj_trn‘)]").click()
 # 5.2 以什么结尾substring()
# driver.find_element_by_xpath("//a[substring(@name,6)=‘news‘]").click()
 # 5.3 包含contains()
# driver.find_element_by_xpath("//a[contains(@name,‘trne‘)]").click()
# 6、使用元素文本定位text()函数
# driver.find_element_by_xpath("//a[text()=‘新闻‘]").click()
driver.find_element_by_xpath("//a[contains(text(),‘新‘)]").click()

这些就是xpath定位最常用的,至于怎么选择使用就看自己具体的使用情况了。

相关推荐