<ul class="meta">
<li class="user">
<img class="classname" src="some url">
givemetext
</li>
</ul>
How do I get the text givemetext with python selenium?
<ul class="meta">
<li class="user">
<img class="classname" src="some url">
givemetext
</li>
</ul>
How do I get the text givemetext with python selenium?
In presented here XML "givemetext" text belongs to <li class="user">
.
So, in order to retrieve this text you have to get that web element and extract it's text.
Something like:
text_value = driver.find_element(By.XPATH,"//li[@class='user']").text
Still need to validate the selected locator is unique, no problem with wait / delay, the element is not inside iframe etc.
The text givemetext is a text node within it's ancestor <li>
.
To print the text givemetext just after the <image>
you can use either of the following Locator Strategies:
Using css_selector:
print(driver.find_element(By.CSS_SELECTOR, "ul.meta li.user").text)
Using xpath:
print(driver.find_element(By.XPATH, "//ul[@class='meta']//li[@class='user'][./img[@class='classname' and @src='some url']]").text)
Ideally you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:
Using CSS_SELECTOR:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul.meta li.user"))).text)
Using XPATH:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//ul[@class='meta']//li[@class='user'][./img[@class='classname' and @src='some url']]"))).text)
Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
You can find a relevant discussion in How to retrieve the text of a WebElement using Selenium - Python