9

Is there a way to get the name of the tag of a Selenium web element?

I found, there is .getTagName() in selenium for Java, in How do I get a parent HTML Tag with Selenium WebDriver using Java?.

Example: In this HTML, if I iterate though class='some_class_name', how can I get the tag_name (h2, p, ul or li)?

<div class='some_class_name'>
    <h2>Some Random Heading 1</h2>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry</p>

    <h2>Some Random Heading 2</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    <p>Random list are:</p>
    <ul>
        <li>Lorem</li>
        <li>Ipsum</li>
        <li>Dolor</li>
    </ul>
</div>

The Python code may look like this...

content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*")
for c in content:
    print(c.getTagName()) # Something like this to get the
                          # tag of inner content...
6
  • Sure you can: driver.find_elements_by_tag_name('li') Makre sure to use elementsinstead of elementin order to get all li tags Commented Oct 12, 2020 at 20:10
  • I appreciate your comment, but I did not want that. I have edited the question. Commented Oct 12, 2020 at 20:18
  • Hey @AnupaM it might help if you give an example of what you expect to find given your example. I'm not following what you mean by tag Name is that the inner HTML? Commented Oct 12, 2020 at 20:26
  • @DanielButler I have made an edit, Hope I am clear now, and will get any solution. Commented Oct 12, 2020 at 20:42
  • Ahh it seems like the problems lies in getting the tag names for elements nested in what the selector finds so in this example the lis. Is that accurate? Commented Oct 12, 2020 at 20:47

1 Answer 1

18

In Python, you have tag_name to get the tag name.

content = driver.find_elements_by_xpath("//div[@class='some_class_name']//child::*")
for c in content:
    print(c.tag_name)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.