How can I print the value of the href attribute?
<a href="aaaaa.pdf"></a>
How can I print the link aaaaa.pdf
with python selenium?
HTML:
<div >
<a href="aaaaa.pdf"></a>
</div>
CodePudding user response:
You can do like this:
print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href'))
CodePudding user response:
div.xxxx a
first, check if this CSS_SELECTOR
is representing the desired element.
Steps to check:
Press F12 in Chrome
-> go to element
section -> do a CTRL F
-> then paste the css
and see, if your desired element
is getting highlighted with 1/1
matching node.
If yes, then use explicit waits:
wait = WebDriverWait(driver, 20)
print(wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.xxxx a"))).get_attribute('href'))
Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
CodePudding user response:
Try the below:
pName = driver.find_element_by_css_selector(".xxxx").text
print(pName)
or
pName = driver.find_element_by_css_selector(".xxxx").get_attribute("href")
print(pName)
CodePudding user response:
The value of the href
attribute i.e. aaaaa.pdf is within the <a>
tag which is the only descendant of the <div>
tag.
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, "div.xxxx > a").get_attribute("href"))
Using xpath:
print(driver.find_element(By.XPATH, "//div[@class='xxxx']/a").get_attribute("href"))
To extract the value ideally you have 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, "div.xxxx > a"))).get_attribute("href"))
Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='xxxx']/a"))).get_attribute("href"))
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