-1
<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?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Andrei
  • 1

2 Answers2

0

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.

Prophet
  • 32,350
  • 22
  • 54
  • 79
  • How do i do that? (Still need to validate the selected locator is unique, no problem with wait / delay, the element is not inside iframe etc.) – Andrei Feb 02 '22 at 11:04
  • These are different issues. To validate the locator is unique you should use the F12 dev tools to see only 1 element on that page is matching that locator. As about waits / delays - I need to see all your code. Generally, after each loading / changing page you have to apply delays to let elements completely loaded before accessing them. Especially when you are going to extract their texts. Expected conditions are the best approach here. presence of iframes are also can be checked with dev tools... – Prophet Feb 02 '22 at 11:08
  • @Andrei Great! https://stackoverflow.com/help/someone-answers – Prophet Feb 02 '22 at 11:51
0

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

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352