Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting href value of a tag of selenium web element

I want to get the url of the link of tag. I have attached the class of the element to type selenium.webdriver.remote.webelement.WebElement in python:

elem = driver.find_elements_by_class_name("_5cq3")

and the html is:

<div class="_5cq3" data-ft="{&quot;tn&quot;:&quot;E&quot;}">
    <a class="_4-eo" href="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1" rel="theater" ajaxify="/9gag/photos/a.109041001839.105995.21785951839/10153954245456840/?type=1&amp;src=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-xfp1%2Ft31.0-8%2F11894571_10153954245456840_9038620401603938613_o.jpg&amp;smallsrc=https%3A%2F%2Fscontent.xx.fbcdn.net%2Fhphotos-prn2%2Fv%2Ft1.0-9%2F11903991_10153954245456840_9038620401603938613_n.jpg%3Foh%3D0c837ce6b0498cd833f83cfbaeb577e7%26oe%3D567D8819&amp;size=651%2C1000&amp;fbid=10153954245456840&amp;player_origin=profile" style="width:256px;">
        <div class="uiScaledImageContainer _4-ep" style="width:256px;height:394px;" id="u_jsonp_2_r">
            <img class="scaledImageFitWidth img" src="https://fbcdn-photos-h-a.akamaihd.net/hphotos-ak-prn2/v/t1.0-0/s526x395/11903991_10153954245456840_9038620401603938613_n.jpg?oh=15f59e964665efe28943d12bd00cefd9&amp;oe=5667BDBA&amp;__gda__=1448928574_a7c6da855842af4c152c2fdf8096e1ef" alt="9GAG's photo." width="256" height="395">
        </div>
    </a>
</div>

I want the href value of the a tag falling inside the class _5cq3.

like image 656
psr Avatar asked Dec 15 '22 12:12

psr


2 Answers

Why not do it directly?

url = driver.find_element_by_class_name("_4-eo").get_attribute("href")

And if you need the div element first you can do it this way:

divElement = driver.find_elements_by_class_name("_5cq3")
url = divElement.find_element_by_class_name("_4-eo").get_attribute("href")

or another way via xpath (given that there is only one link element inside your 5cq3 Elements:

url = driver.find_element_by_xpath("//div[@class='_5cq3']/a").get_attribute("href")
like image 131
drkthng Avatar answered Dec 18 '22 12:12

drkthng


You can use xpath for same

If you want to take href of "a" tag, 2nd line according to your HTML code then use

url = driver.find_element_by_xpath("//div[@class='_5cq3']/a[@class='_4-eo']").get_attribute("href")

If you want to take href of "img" tag, 4nd line according to your HTML code then use

url = driver.find_element_by_xpath("//div[@class='_5cq3']/a/div/img[@class='scaledImageFitWidth img']").get_attribute("href")
like image 21
Shubham Jain Avatar answered Dec 18 '22 11:12

Shubham Jain