问题
I'm very confused by getting text using Selenium.
There are span
tags with some text inside them. When I search for them using driver.find_element_by_...
, everything works fine.
But the problem is that the text can't be got from it.
The span
tag is found because I can't use .get_attribute('outerHTML')
command and I can see this:
<span class="branding">ThrivingHealthy</span>
But if I change .get_attribute('outerHTML')
to .text
it returns empty text which is not correct as you can see above.
Here is the example (outputs are pieces of dictionary):
display_site = element.find_element_by_css_selector('span.branding').get_attribute('outerHTML')
'display_site': u'<span class="branding">ThrivingHealthy</span>'
display_site = element.find_element_by_css_selector('span.branding').text
'display_site': u''
As you can clearly see, there is a text but it does not finds it. What could be wrong?
EDIT: I've found kind of workaround. I've just changed the .text
to .get_attribute('innerText')
But I'm still curious why it works this way?
回答1:
The problem is that there are a LOT of tags that are fetched using span.branding
. When I just queried that page using find_elements
(plural), it returned 20 tags. Each tag seems to be doubled... I'm not sure why but my guess is that one set is hidden while the other is visible. From what I can tell, the first of the pair is hidden. That's probably why you aren't able to pull text from it. Selenium's design is to not interact with elements that a user can't interact with. That's likely why you can get the element but when you try to pull text, it doesn't work. Your best bet is to pull the entire set with find_elements
and then just loop through the set getting the text. You will loop through like 20 and only get text from 10 but it looks like you'll still get the entire set anyway. It's weird but it should work.
来源:https://stackoverflow.com/questions/32301175/selenium-cant-get-text-from-span-element