Python selenium get tag value of a selected element

Question:

I’m using the code below to find all the elements with class value = “ng_isolate_scope”. What I would need to do though is to capture the tag value of the selected elements, since I need this information for further analysis

<span class="ng-isolate-scope">
<div class="ng-isolate-scope">

Code:

elems = driver.find_elements_by_class_name("ng-isolate-scope")
for elem in elems:
    tag_value = elem.get_tag()
    print("element found with tag value = " + str(tag_value))

However, tag_value() doesn’t exist. What can I do to capture the tag value of an element?
Thanks

Asked By: Angelo

||

Answers:

If I right understand, you want a text of a tag:

elems = driver.find_elements_by_class_name("ng-isolate-scope")
for elem in elems:
    tag_value = elem.text # get text of an element
    print("'element found with tag value = " + tag_value + "'")

for example:

<span class="ng-isolate-scope">span tag</span>
<div class="ng-isolate-scope">div tag</div>

will produce:

'element found with tag value = span tag'
'element found with tag value = div tag'

EDIT:

from bs4 import BeautifulSoup
from html.parser import HTMLParser

driver = webdriver.Chrome()
driver.get("https://stackoverflow.com/questions/51789088/python-selenium-get-tag-value-of-a-selected-element/51789139#51789139")
parsed_html = BeautifulSoup(driver.page_source) # get HTML

list = list() # create a list

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs): # get start tags
        list.append(tag) # store them in the list


parser = MyHTMLParser()
parser.feed(str(parsed_html.body.find('div', attrs={'id':'question-header'}))) # feed parser with parsed HTML

print(list[0]) # first element in the list is the tag you need

Output:

div

Reference to the documentation.

Answered By: Andrei Suvorkov

updated:
Its bit tricky, here my approach is to get outerHTML of element and then splitting the first word (which is tag name). So you can try:

    elements = driver.find_elements_by_class_name("ng-isolate-scope")
    for element in elements:
      outerhtml = element.get_attribute('outerHTML ') // to extract outerHTML 
      tag_value=outerhtml.split('',1)[0] // to extract first word
      print("element found with tag value = " + tag_value)
Answered By: theGuy

you can do this by get the tagName attribute directly, without need to parsing the outerHTML:

elements = driver.find_elements_by_class_name("ng-isolate-scope")
for element in elements:
  tag_name = element.get_attribute('tagName')
  print(tag_name) ## INPUT / A / BUTTON
Answered By: Eri Indrawan
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.