Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get_text() or text property is not working for labels

I want to access the text of labels, but neither get_text() nor text property is working for the following HTML:

<label class="checkbox">
<input type="checkbox" value="BATSMC">
BATS Multicast PITCH
</label>

For example, here I want to get the value: BATS Multicast PITCH.

In Selenium-Python code:

print e.text 

is giving blank spaces and get_text() is giving the following error:

AttributeError: 'WebElement' object has no attribute 'get_text'

I am getting the correct web element and am able to access other properties like size, location, parent etc. I expected "text" to work. Can anyone help?

like image 782
selenium_user Avatar asked Mar 06 '14 16:03

selenium_user


Video Answer


1 Answers

The <label> tag in the above HTML does not have a text attribute.

If you want to retrieve the BATS Multicast PITCH string, then you need to get it from the <input> tag instead. For example, the following code will print this string:

e = driver.find_element_by_tag_name('input')
print e.text

If you want to retrieve the entire inner HTML of the <label> tag, then you can use:

e = driver.find_element_by_tag_name('label')
print e.get_attribute('innerHTML')

This will print "<input type="checkbox" value="BATSMC">BATS Multicast PITCH.

Of course, you probably have other <label> and <input> tags in your HTML, so you'll need to use a different method (other than find_element_by_tag_name) in order to find these specific elements.

BTW, I just noticed that the <input> tag in the HTML above is not properly closed...

like image 89
barak manos Avatar answered Oct 29 '22 18:10

barak manos