Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get links within a subelement in selenium?

I have the following html code:

   <div id="category">    //parent div
    <div class="username"> // n-number of elements of class username which all exist within parent div
      <a rel="" href="link" title="smth">click</a>          
    </div> 
    </div> 

I want to get all the links witin the class username BUT only those within the parent div where id=category. When I execute the code below it doesn´t work. I can only access the title attribute by default but can´t extract the link. Does anyone have a solution?

  a = driver.find_element_by_id('category').find_elements_by_class_name("username")
    links = [x.get_attribute("href") for x in a]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use the following css selector which will return all the anchor tags.

links = [x.get_attribute("href") for x in driver.find_elements(By.CSS_SELECTOR,"#category > .username >a")]

Or

links = [x.get_attribute("href") for x in driver.find_elements_by_css_selector("#category > .username >a")]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading