- 定义:XPath即为XML路径语言,它是一种用来确定XML文档中某部分位置的语言
- Xpath属性定位:
- 常用属性
-
from selenium import webdriver import time driver=webdriver.Firefox() driver.get("https://www.baidu.com") time.sleep(3) #xpath通过id定位到输入框,并搜索python driver.find_element_by_xpath("//*[@id='kw']").send_keys("python") #xpath通过name定位到输入框,并搜索python driver.find_element_by_xpath("//*[@name='wd']").send_keys("python") #xpath通过class定位到输入框,并搜索python driver.find_element_by_xpath("//*[@class='s_ipt']").send_keys("python")
- 其他属性
-
from selenium import webdriver import time driver=webdriver.Firefox() driver.get("https://www.baidu.com") time.sleep(3) #xpath通过autocomplete定位到输入框,并搜索python driver.find_element_by_xpath("//*[@autocomplete='off']").send_keys("python")
- xpath标签
- 有些时候有多个同名的属性,可以选用标签做筛选
- *可代表任意标签
-
from selenium import webdriver import time driver=webdriver.Firefox() driver.get("https://www.baidu.com") time.sleep(3) #xpath通过autocomplete定位到输入框,并搜索python driver.find_element_by_xpath("//input[@autocomplete='off']").send_keys("python") driver.find_element_by_xpath("//*[@autocomplete='off']").send_keys("python")
- XPath层级
- 如果一个元素,属性不太明显,可以根据父元素定位到需要的层级
-
from selenium import webdriver import time driver=webdriver.Firefox() driver.get("https://www.baidu.com") time.sleep(3) #xpath通过层级定位到输入框,并搜索python #多级查询,form/span/input driver.find_element_by_xpath("//form[@id='form']/span/input").send_keys("python") #父查询,span/input driver.find_element_by_xpath("//span[@class='bg s_ipt_wr iptfocus quickdelete-wrap']/input").send_keys("python")
- Xpath索引
- 当一个元素其兄弟段素标签完全一样时,无法通过层级来定位,可以通过显示的 先后顺序来索引(索引从1开始)
- XPath逻辑运算
- 与(and),或(or),非(not)
-
from selenium import webdriver import time driver=webdriver.Firefox() driver.get("https://www.baidu.com") time.sleep(3) #xpath通过逻辑运算定位到输入框,并搜索python driver.find_element_by_xpath("//*[@id='kw' and @name='wd']").send_keys("python")
- 模糊匹配
-
from selenium import webdriver import time driver=webdriver.Firefox() driver.get("https://www.baidu.com") time.sleep(3) #xpath模糊匹配 driver.find_element_by_xpath("//*[contains(text(),'hao123')]").click() #xpath模糊匹配某个属性 driver.find_element_by_xpath("//*[contains(@id,'kw')]").send_keys("python") #xpath模糊匹配以什么开头 driver.find_element_by_xpath("//*[starts-with(@id,'k')]").send_keys("python") #xpath模糊匹配text driver.find_element_by_xpath("//*[text()='hao123']").click()
-
转载于:https://www.cnblogs.com/Arcy/p/11094152.html