1

I am trying to extract a text from <div>, which is an inside double quote (refer Screenshot) with XPath

<div class="two columns" style="font-size: 18px; padding-top: 5px;">
  <img src="images/spins_s.png" border="0" style="margin-bottom: -1px;"> 
   5
</div>

I am attaching a screenshot here, [ https://i.stack.imgur.com/uOmeS.png][1] While i am trying this xpath expression in cole log its return correct o/p,

>>$x("//div[@class='two columns']/img[@src='images/spins_s.png']/..")[0].innerText
>>" 5"

But when I am going to run this code In python

spin_balance = browser.find_element_by_xpath("//div[@class='two columns']/img[@src='images/spins_s.png']/..")[0].innerText

it's giving error like this

spin_balance = browser.find_element_by_xpath("//div[@class='two columns']/img[@src='images/spins_s.png']/..")[0].innerText
TypeError: 'WebElement' object is not subscriptable

Image of HTML: image

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

1 Answers1

0

The text 5 is within a text node. So to print the text you have to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.two.columns"))).text)
    
  • Using XPATH and text attribute:

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='two columns']"))).text)
    
  • Using XPATH and childNodes:

    print(driver.execute_script('return arguments[0].lastChild.textContent;', WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='two columns'][./img[@src='images/spins_s.png']]")))).strip())
    
  • Using XPATH and splitlines():

    print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='two columns'][./img[@src='images/spins_s.png']]"))).get_attribute("innerHTML").splitlines()[2])
    
  • 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
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352