4

Here is the html Hi I want to locate the href element connected to a student named "John Doe" based on the following-sibling input value of 'ST'. This the code im using to select the element:

driver.find_element_by_xpath('//a[following-sibling::input[@value="ST"]]/@href').click()

It's locating the correct element but im getting this error:

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//a[following-sibling::input[@value="ST"]]/@href" is: [object Attr]. It should be an element.

How can I fix this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
terence vaughn
  • 521
  • 2
  • 11
  • 23

1 Answers1

0

This error message...

selenium.common.exceptions.InvalidSelectorException: Message: invalid selector: The result of the xpath expression "//a[following-sibling::input[@value="ST"]]/@href" is: [object Attr]. It should be an element.

......implies that your XPath expression was not a valid xpath expression.


For the record Selenium WebDriver supports xpath-1.0 only which returns the set of node(s) selected by the xpath.

You can find the specifications in XML Path Language (XPath) Version 1.0

Where as the xpath expression you have used:

driver.find_element_by_xpath('//a[following-sibling::input[@value="ST"]]/@href')

Is a xpath-2.0 based expression and would typically return an object Attr. A couple of examples:

  • //@version: selects all the version attribute nodes that are in the same document as the context node
  • ../@lang: selects the lang attribute of the parent of the context node

You can find the specifications in XML Path Language (XPath) 2.0 (Second Edition)


Solution

To locate the desired element with a href attribute connected to a student named "John Doe" based on the following-sibling input value of ST you can use either of the following based Locator Strategies:

  • Using preceding:

    driver.find_element_by_xpath("//input[@value='ST']//preceding::a[1]").click()
    
  • Using preceding-sibling:

    driver.find_element_by_xpath("//input[@value='ST']//preceding-sibling::a[@href]").click()
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • I am not an expert on xpath but it seems if you reach an attribute you can always access its parent element by adding a /.. [slash double dot] at the end i.e. : `"//@*[name()='xml:id' and .='corr1']/.."` – Ahmad Nadeem Nov 11 '22 at 07:34