selenium how to get the content of href within some targeted class


I am trying to retrieve the data from the webpage has the html in below

       <div class="someclass">
       <p class="name"><a href="#/word/1/">helloworld</a></p>

My goal is to parse “#/word/1/”
What I did is

        target = self.driver.find_element_by_class_name('someclass')
        print target
        print target.text
        print target.get_attribute("css=a@href")
        print target.tag_name

but the output are

 <selenium.webdriver.remote.webelement.WebElement object at 0x10bf16210>

I tried so many ways , it seems there is no way i can get the content of ‘a href’ within the targeted class.

I really dont want to do is get the source code of the page, and then do a string searching, that seems dumb….

anyway to get that?

Asked By: runcode



As far as I am aware you can get the href by searching through the child elements

div = self.driver.find_element_by_class_name('someclass')
Answered By: aychedee

This should do it for you:

self.driver.find_element_by_css_selector('.someclass a').get_attribute('href')
Answered By: Andrew

if you search for special tag use from find_element_by_id or classname or xpath
and then use get_attribute(‘href’)

in this example print all attribute for a tags

   ids = self.driver.find_elements_by_xpath('//*[@href]')
   for id in ids:
Answered By: mamal

This should do it:

div = driver.find_element(By.CLASS_NAME, 'abcxyz')
content = driver.find_element(By.LINK_TEXT,'Click_Me').get_attribute('href')

Iam using selenium==4.7.2

Answered By: Abhi
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.