【问题标题】:How to access xpath with index number in selenium python?如何在 selenium python 中使用索引号访问 xpath?
【发布时间】:2021-06-15 05:38:52
【问题描述】:

我只想访问 xpath。但是当我在检查菜单中搜索它时,它会找到 5 个结果。我想访问其中一个而不是 5。我怎样才能用索引号呢?喜欢...

xpath = "//a[@role='button']" # 5 elements available with this xpath
modified_xpath = "//a[@role='button'][2]" # I'm trying with the index number.
driver.find_element_by_xpath(modified_xpath).click() # But It's not working.

它不工作!

【问题讨论】:

  • find_elements_by_xpath 返回一个列表,删除xpath中的索引查找并索引到返回的列表中? driver.find_elements_by_xpath(modified_xpath)[2]
  • 错误是什么?分享页面的 HTML 或 URL
  • 显示这个错误selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: Unable to locate an element with the xpath expression //a[@role='button'] because of the following error: SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//a[@role='button']' is not a valid XPath expression.

标签: python selenium xpath


【解决方案1】:

你可以像这段代码那样做--

    xpath = "//a[@role='button']" 
    xpaths = driver.find_elements_by_xpath(xpath)
    xpaths[2].click()

希望它会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 2016-07-28
    • 1970-01-01
    • 2014-09-15
    • 2017-11-27
    • 1970-01-01
    相关资源
    最近更新 更多