0

I'm currently trying to execute this command, trying to select:

driver.find_element_by_xpath("//a[contains(@href, 'mailto')]/@href").getAttribute("href") 

To get X when <a href="X">.

enter image description here

It shows me this error:

invalid selector: The result of the xpath expression "//a[contains(@href, 'mailto')]/@href" is: [object Attr]. It should be an element.

I have tryed .getAttribute but without success. Could anyone help me with this ?

Thanks

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Always add code and markup as text, and format it as code. Images cannot easily be searched or copy-and-pasted to verify solutions. Thanks. – kjhughes Nov 16 '21 at 21:23

2 Answers2

3

When you use find_element_by_xpath, you should supply an XPath expression that selects elements not one that selects attributes.

So drop the final /@href.

Michael Kay
  • 156,231
  • 11
  • 92
  • 164
1

This error message...

invalid selector: The result of the xpath expression "//a[contains(@href, 'mailto')]/@href" is: [object Attr]. It should be an element.

...implies that the xpath expression "//a[contains(@href, 'mailto')]/@href" is an invalid expression as it returns an object attribute where as Selenium expects an WebElement.

A quick solution would be to drop the /@href part from the fag end of the xpath.


Comprehensive Solution

To print the value of the href attribute you can use either of the following Locator Strategies:

  • Using css_selector:

    print(driver.find_element_by_css_selector("a.[href*='mailto']").get_attribute("href"))
    
  • Using xpath:

    print(driver.find_element_by_xpath("//a[starts-with(@href, 'mailto')]").get_attribute("href"))
    

Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "//a[starts-with(@href, 'mailto')]"))).get_attribute("value"))
    
  • Using XPATH:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='name' and @title='Download']"))).get_attribute("value"))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352