'Selenium Python: how to get a list of all strings in a tag
I am trying to get text ("Get this text") inside the following html using this Xpath: "//span[@id='myanswer']/text()[7]". It finds the text on the website when I put it in the cntrl+F field in the inspect html part, but when I try to print the output in my python code it returns nothing. Also doing something like
driver.find_element(By.XPATH,"//span[@id='myanswer']").text,
also returns nothing. So I'm thinking maybe appending all those strings into a list and printing the last element of that list? Is there any way of printing out this last string?
<span id="myanswer">
<br>
<br>
" [ "
<b>tU</b>
" method Response ]"
<br>
" "
<span class="text-success"><i class="fa fa-angle-double-right"></i></span>
<strong></strong>
" "
<span class="text-secondary"><i>string</i></span>
<b>:</b>
"
Get this text"
<br>
<br>
</span>
Solution 1:[1]
So I'm thinking maybe appending all those strings into a list and printing the last element of that list
- This is one of the good ways to deal with this text node.
If
driver.find_element(By.XPATH,"//span[@id='myanswer']").text
did not return anything then there could multiple reason:
1.
//span[@id='myanswer'] is not unique in HTMLDOM.
Steps to check for uniqueness:
Press F12 in Chrome -> go to element section -> do a CTRL + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.
Maybe you are missing a delay, Please put a sleep or use Explicitwait like below:
WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@id='myanswer']"))).get_attribute('innerText')
Imports:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
