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">
.
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
CodePudding user response:
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
.
CodePudding user response:
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.
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