Home > Back-end >  Selenium invalid selector: Unable to locate an element with the xpath expression error
Selenium invalid selector: Unable to locate an element with the xpath expression error

Time:11-29

I am failing to select the span than contains Full Name:

No matter what selector I use, I always get the error:

Message: invalid selector: Unable to locate an element with the xpath expression

For example I have tried:

xpath = "//a[@class='app-aware-link']/span[@dir='ltr']/span[@aria-hidden='true']"
xpath = "//a[@class='app-aware-link']/span[@dir='ltr']"

Also full xpath that are valid in console $x(xpath), not valid with Selenium

<div >
   <span >
      <span >
         <a  href="https://www.linkedin.com/in/inge-de-grauwe-6ab2a98?miniProfileUrn=urn:li:fs_miniProfile:ACoAAAF3gqMBfw45cjhzEVAqNU943iCK0siy3fU" data-test-app-aware-link="">
            <span dir="ltr">
               <span aria-hidden="true">
                  <!---->Inge De Grauwe<!---->
               </span>
               <span >
                  <!---->View Inge De Grauwe’s profile<!---->
               </span>
            </span>
         </a>
         <span >
            <div >
               <!---->    
               <span >
                  <span aria-hidden="true">
                     <!---->• 1st<!---->
                  </span>
                  <span >
                     <!---->1st degree connection<!---->
                  </span>
               </span>
            </div>
         </span>
      </span>
   </span>
   <span aria-hidden="true" >
      <div >
         <!---->    
         <span >
            <span aria-hidden="true">
               <!---->• 1st<!---->
            </span>
            <span >
               <!---->1st degree connection<!---->
            </span>
         </span>
      </div>
   </span>
</div>

If I use

xpath = "//a[contains(@class,'app-aware- 
link')]/span[@dir='ltr']/span[@aria-hidden='true']"

The error still:

Unable to locate an element with the xpath expression driver.find_elements(By.XPATH, '//a[contains(@class,'app-aware-link')]/span[@dir='ltr']/span[@aria-hidden='true']') because of the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string 'driver.find_elements(By.XPATH, '//a[contains(@class,'app-aware-link')]/span[@dir='ltr']/span[@aria-hidden='true']')' is not a valid XPath expression.

CodePudding user response:

Your problem is with first part of the XPath //a[@class='app-aware-link']. The value of class attribute there is "app-aware-link " with a space after "app-aware-link". That's why "//a[@class='app-aware-link']/span[@dir='ltr']/span[@aria-hidden='true']" doesn't match nothing there.
So, to make your code working you can change the XPath in 2 ways:

xpath = "//a[@class='app-aware-link ']/span[@dir='ltr']/span[@aria-hidden='true']"

Or

xpath = "//a[contains(@class,'app-aware-link')]/span[@dir='ltr']/span[@aria-hidden='true']"
  • Related