How to access tags (get values like text of tags) inside a tag? How to get value of h1 tag inside a (paragraph) p tag?

Viewed 529

I am working with Selenium with Python to solve a problem. I want to extract information inside a paragraph (p tag). I am using "find_elements_by_tag_name" to locate all the p tags in the page. But how can I access some tags that are already inside that paragraph. For example there is html file which ahs a code like

<p> This is a paragraph <h1> but this is a h1 tag </h1></p>

I have used selenium to open the page like

br=webdriver.Chrome()
br.get('file:///C:/Users/Shady/Desktop/New%20Text%20Document.html')

I am able to access the elements of the the P tag by

p_tags=br.find_elements_by_tag_name('p')

It shows only one element and when I do

print(x[0].text)

it shows only

This is a paragraph

How can I access the h1 tag inside the p tag. Can X_path would work? if Yes, Can you please share the code?

1 Answers

The <h1> tag is actually a descendent of the <p> tag. So in your code trials you have identified the <p> tag and extracted the text which correctely gave This is a paragraph.

So to extract the text but this is a h1 tag you have to reach to the descendent <h1> and you can use either of the following Locator Strategies:

  • Using css_selector:

    print(driver.find_element_by_css_selector("p>h1").get_attribute("innerHTML"))
    
  • Using xpath:

    print(driver.find_element_by_xpath("//p/h1").get_attribute("innerHTML"))
    
Related