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.
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.
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.
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.
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With