'Python Selenium: How can I print the link?
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 class="xxxx">
<a href="aaaaa.pdf"></a>
</div>
Solution 1:[1]
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
Solution 2:[2]
You can do like this:
print(driver.find_element_by_css_selector(".xxxx a").get_attribute('href'))
Solution 3:[3]
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)
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | cruisepandey |
| Solution 2 | |
| Solution 3 | Akzy |
| Solution 4 | undetected Selenium |
