Home > front end >  Why is .text always empty?
Why is .text always empty?

Time:10-05

I've tried using getText() Referencing, but when I use that method I always get the error "WebElement object has no attribute getText()". I found .text through a YouTube video but I'm not getting results from it either. Any thoughts?

from selenium import webdriver

driverPath = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(driverPath)


driver.implicitly_wait(20)
driver.get ('https://shop.pricechopper.com/search?search_term=lettuce')

pageSource = driver.page_source

search = driver.find_elements_by_class_name ("css-dr3s47")
print (search[0].text)



driver.quit()

CodePudding user response:

You are using Selenium with Python, so correct method is .text

.getText() is for Selenium-Java Bindings.

The reason why are you getting null is cause elements are not rendered properly and you are trying to interact with them resulting in null.

Please use Explicit wait or time.sleep() which is worst case to get rid of this issue.

Also, there's a pop window that we will have to click on close web element, so that css-dr3s47 will be available to Selenium view port.

Code :

driver = webdriver.Chrome(driver_path)
driver.maximize_window()
driver.implicitly_wait(30)
wait = WebDriverWait(driver, 30)
driver.get("https://shop.pricechopper.com/search?search_term=lettuce")
try:
    wait.until(EC.element_to_be_clickable((By.XPATH, "//button[@ng-click='processModalCloseClick()']"))).click()
    print('Clicked on modal pop up closer button')
except:
    pass

search = driver.find_elements_by_class_name ("css-dr3s47")
print (search[0].text)

Imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

CodePudding user response:

getText returns elements with rendered size more than 0 * 0 , so if element is not displayed of has size zero , then it wont return anything .

Two things you could do is :

  1. scroll to the element before getting text
 Actions actionProvider = new Actions(driver);
  // Performs mouse move action onto the element
  actionProvider.moveToElement(search[0]).build().perform();
  print(search[0].text)
  1. Use textCOntent

Text content doesn't check for display or size , it just gives content

    print(search[0].get_attribute("textContent"))
  • Related