Morpheus
Morpheus

Reputation: 3523

How to locate the href value of a link in a webpage by selnium in Python

I have a webpage that contains a table of 1 row and it contains a link. I would like to get the href of the link.

<table class="Table__table___3G1SW">
    <caption>My Cpation</caption>
    <colgroup><col class="Table__col-12___1AM3h"></colgroup>
    <thead>
        <tr><th scope="col"> Name, XYZ, Hel</th></tr>
    </thead>
    <tbody><tr><td><div><div><a href="/staff/312577">
        <div><!-- react-text: 535 -->KLMNOP<!-- /react-text --><!-- react-text: 536 -->,<!-- /react-text --><!-- react-text: 537 --> <!-- /react-text --><!-- react-text: 538 -->ABCDEF<!-- /react-text --><!-- react-text: 539 --> <!-- /react-text --><!-- react-text: 540 -->B<!-- /react-text --></div></a></div><p>HOMNTH &amp; XYZ</p><div><div><div>LLLMMMNN</div><div></div><div><!-- react-text: 547 -->NEW GBEL,<!-- /react-text --><!-- react-text: 548 --> <!-- /react-text --><!-- react-text: 549 -->NP<!-- /react-text --><!-- react-text: 550 --> <!-- /react-text --><!-- react-text: 551 -->085362!-- /react-text --></div></div></div></div></td></tr>
    </tbody>
</table>

I would like to get the value of /staff/312577 and I tried using xpath but I was unsuccessful

elm = browser.find_element_by_xpath('//table[@class="Table__table___3G1SW"]//a[]')

I know that I am making a mistake as I am not specifying the a value but I am unsure how to isolate the href value.

Upvotes: 0

Views: 111

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193058

To extract the value of href attribute i.e. /staff/312577 you can use the following Locator Strategy:

myText = driver.find_element_by_xpath("//table[contains(@class,'Table__table___')]/caption[contains(.,'My Cpation')]//following::tbody[1]/tr/td//a").get_attribute("href")

Upvotes: 1

Druta Ruslan
Druta Ruslan

Reputation: 7402

try this i think it will work, you have a mistake at the end of xpath need to be //a not //a[], and after this simple use get_attribute() method

elm = browser.find_element_by_xpath('//table[@class="Table__table___3G1SW"]//a')
print(elem.get_attribute('href'))

Output

'/staff/312577'

Upvotes: 1

Related Questions