前面学习了 CSS 选择元素的方法,用起来十分灵活。
但有时候使用 xpath 更加方便,爬虫 Scrapy 和 Appium APP 自动化都支持 Xpath 元素选择。
学习的时候可以参考这个简单的页面:https://git-jhy.github.io/snake,右键检查,在 Elements 中 Ctrl+F 可以搜索元素
1. 路径
绝对路径
/
可以表示根节点,也可以用在标签后表示直接子节点的关系,类似 CSS 中的 >
如 /html 和 /html/body/div
,后者等价于 html>body>html
,通过 xpath 查找元素方法如下:
1
2elements = driver.find_elements_by_xpath("/html/body/div")
相对路径
使用 //
表示相对路径,它表示从当前节点向后查找元素,不管出现在什么位置:
1
2elements = driver.find_elements_by_xpath("//div//li")
它等价于 CSS 选择器 div li
同理,//div/li
等价于 div > li
通配符
使用 *
选择所有元素,如:
1
2
3
4elements = driver.find_elements_by_xpath("//div/ul/li") for element in elements: print(element.get_attribute('outerHTML'))
2. 属性选择
语法格式:
1
2[@attributeName='attributeValue']
ID 属性
选择 ID 为 fruits 的元素:
1
2//*[@id='fruits']
class 属性
选择 class 为 green 的元素
1
2//*[@class='green']
选择 class 为 like tomato 的元素(所有 class 都要列写出来)
1
2//*[@class='like tomato']
contains
选择 class 包含 tomato 属性的元素
1
2//*[contains(@class, 'tomato')]
选择 style 包含 color 字符串的元素
1
2//*[contains(@style, 'color')]
选择 style 属性值以 color 开头的元素(结束使用 ends-with)
1
2//*[starts-with(@style, 'color')]
3. 次序选择
第 k 个子元素
选择满足条件的第二个子元素:
1
2//div[@id='fruits']//ul//li[2]
此时在 页面 选中的是第二个水果
倒数第 k 个子元素
选择最后一个、倒数第 2 个 li
标签:
1
2
3//li[last()] //li[last()-1]
范围选择
选择前 3 个 li 元素
1
2//li[position()<=3]
4. 组选择、父节点和兄弟节点
组选择
CSS 可以使用逗号分隔多个表达式,进行多个匹配,xpath 可以使用 |
实现组选择:
1
2//div | //strong
等价于 CSS 选择:
1
2div, strong
父节点
可以使用 /..
向上查找父节点,如查找 id 为 fruits 的 div 标签的父节点的父节点:
1
2//div[@id='fruits']/../..
兄弟节点
CSS 选择兄弟节点用 + ,而 xpath 中:
前兄弟节点:/preceding-sibling::
后兄弟节点:/following-sibling::
如选择第 3 个 li 标签前面为 li 标签的兄弟节点:
1
2//div[@id='fruits']//li[3]/precedding-sibling::li
5. 实战小测试
运行下面的代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19import time from selenium import webdriver driver = webdriver.Chrome() driver.get('https://git-jhy.github.io/snake') driver.implicitly_wait(8) # 选择 class 包含 tomato 的元素 tomato = driver.find_element_by_xpath('//*[contains(@class, "tomato")]') print(tomato.get_attribute('outerHTML'), 'n') # 选择前 3 种水果 fruits = driver.find_elements_by_xpath('//div[@id="fruits"]//li[position()<=3]') for fruit in fruits: print(fruit.text, end=', ') # 选择第 2 种蔬菜 print('n') vegetable = driver.find_element_by_xpath('//div[@id="vegetable"]//li[2]') print(vegetable.get_attribute('outerHTML')) time.sleep(1) driver.quit()
结果为:
1
2
3
4
5<li class="like tomato">tomato</li> apple, banana, cherry, <li class="dislike">been</li> ***Repl Closed***
REFERENCE:
- https://git-jhy.github.io/snake
- https://developer.mozilla.org/zh-CN/docs/Web/XPath
- http://www.python3.vip/tut/auto/selenium/xpath_1/
最后
以上就是自觉帽子最近收集整理的关于使用 xpath 选择元素1. 路径2. 属性选择3. 次序选择4. 组选择、父节点和兄弟节点5. 实战小测试的全部内容,更多相关使用内容请搜索靠谱客的其他文章。
发表评论 取消回复