pythonselenium

Find element by tag name within element by tag name (Selenium)


I want to print all the href(links) from a website. All these hrefs are stored in an 'a' tag, and these a tags are stored in a 'li' tag. Now, I know how to select all the li's. I need a way to select all the a's within the li's to get the 'href' attribute. Tried the following but doesn't really work.

li = driver.find_elements_by_tag_name('li')
for link in li:
     a_childrens = link.find_element_by_tag_name('a')

for a in a_children
     (print a.get_attribute('href'))

Thanks in advance.


Solution

  • I recommend css_selector instead of tag_name

    aTagsInLi = driver.find_elements_by_css_selector('li a')
    for a in aTagsInLi:
         (print a.get_attribute('href'))