简体   繁体   中英

How to get the text inside a h2 tag in selenium python

how to get the text inside the html tag and assert if it is present on the page.

html-

<h2>  You are suggested the Low Fat Vegan Diet </h2>

i tried-

message = driver.find_elements_by_tag_name('h2').Text()

AttributeError: 'list' object has no attribute 'Text'

 message = driver.find_elements_by_tag_name('h2').getText()

AttributeError: 'list' object has no attribute 'getText'

how do i get the text and assert it is present in the page?

the method name is find_elements_by_tag_name so it returns a list of elements . if your target element is the first item in elements you can try this:

message = driver.find_elements_by_tag_name('h2')[0].text

i recommend you to use Beautifulsoup to get better search in elements.

It's hard to tell without the full HTML, but if you have multiple h2 elements you will need to iterate through them to get the text.

message = driver.find_elements_by_tag_name('h2')
for i in message:
    print(i.text) 

Otherwise, you should be able to select the text with .text

message = driver.find_elements_by_tag_name('h2').text

you could use

//h2[contains(text(),'String value')]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM