Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 477
Jesse Avatar asked Oct 13 '16 13:10

Jesse


People also ask

How do I find an element by tag name?

We can find an element using the element tag name with Selenium webdriver with the help of locator tagname. To locate an element with tagname, we have to use the By. tagName method. In the above image, the text – You are browsing the best resources for has the h4 tag.

What is tagname in xpath?

tagname: Name of the tag of a particular node. @: Used to select the select attribute. Attribute: Name of the attribute of the node. Value: Value of the attribute.

What is tagname in Selenium?

In this case, Selenium will select or locate the first tag that matches the one provided from your end. So, refrain yourself from using tag name locator in Selenium if you intend to locate a single element. The command to identify an element via tag name in Selenium is: driver.findElement(By.tagName("input")); 1.

How do I get tagname in Selenium?

To get the tag name of a web element programmatically using Selenium in Java, use WebElement. getTagName() function. We first find the web element by name, id, class name, etc., and then call the getTagName() function on this web element.


1 Answers

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'))
like image 70
Buaban Avatar answered Oct 10 '22 09:10

Buaban