如何在Selenium Python中使用索引号访问XPath?

3

我只想访问一个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 returns a list, remove the index lookup in the xpath and index into the returned list? driver.find_elements_by_xpath(modified_xpath)[2] - Iain Shelvington
什么是错误?分享页面的HTML或URL。 - cruisepandey
显示以下错误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. - Priya
1个回答

2
您可以按照以下代码进行操作--
    xpath = "//a[@role='button']" 
    xpaths = driver.find_elements_by_xpath(xpath)
    xpaths[2].click()

希望它能够正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接