python - 使用 xpath 按位置查找元素

标签 python selenium xpath

我的 selenium 驱动程序找到了大约 13 个 li 元素。但是,以下内容不起作用,出现找不到元素的错误:

driver.find_element_by_xpath('//li[0]')

但是,这可以正常工作:

driver.find_elements_by_xpath('//li')[0]

我认为这些是相同的,尽管我更喜欢第一种方法。这是怎么回事?

最佳答案

Python 是零索引的,但是 XPath is one-indexed :

The first position is 1.

因此,以下是等价的:

driver.find_elements_by_xpath('//li')[0]
driver.find_element_by_xpath('(//li)[1]')

关于python - 使用 xpath 按位置查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49266162/

相关文章:

html - 如何在 iOS 上将格式不正确的 html 转换为 xhtml

javascript - 如何在 node.js 中通过 XPath 更改带有 xmldom 的 DOM?

python - 自动创建有效链接

python - 用变量打破循环 - Python

python - 使用 Jinja 过滤器创建内容片段

python - 求素数函数

java - 无法使用 html 发送超链接 key

c# - 如何通过 Selenium 获取 Chrome 上当前事件的选项卡索引?

javascript - 如何在 C# 中单击带有 Selenium 的 JS 链接

javascript - 无法使用 python selenium 获取生成的 html 源