【问题标题】:Why is .text always empty?为什么 .text 总是空的?
【发布时间】:2021-10-05 05:13:57
【问题描述】:

我尝试过使用 getText() Referencing,但是当我使用该方法时,我总是收到错误 "WebElement object has no attribute getText()"。我通过 YouTube 视频找到了 .text,但我也没有从中得到结果。有什么想法吗?

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()

【问题讨论】:

  • 代替.text 试试.get_attribute("innerText")。看看这是否有效。
  • 你也可以尝试模拟 api 请求而不是抓取
  • 感谢您的回复,几乎所有建议的解决方案都有效。

标签: python python-3.x selenium selenium-chromedriver


【解决方案1】:

您正在使用 Selenium 和 Python,所以正确的方法是 .text

.getText() 用于 Selenium-Java 绑定

你得到 null 的原因是元素没有正确渲染,你试图与它们交互导致 null。

请使用 Explicit waittime.sleep() 这是最坏的情况来解决此问题。

此外,还有一个弹出窗口,我们必须单击关闭 web 元素,以便 css-dr3s47 可用于 Selenium 视图端口。

代码:

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)

进口:

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

【讨论】:

    【解决方案2】:

    getText 返回渲染大小大于 0 * 0 的元素,因此如果元素未显示的大小为零,则它不会返回任何内容。

    你可以做的两件事是:

    1. 在获取文本之前滚动到元素
     Actions actionProvider = new Actions(driver);
      // Performs mouse move action onto the element
      actionProvider.moveToElement(search[0]).build().perform();
      print(search[0].text)
    
    1. 使用文本内容

    文本内容不检查显示或大小,它只是提供内容

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

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 2020-07-11
      • 1970-01-01
      • 1970-01-01
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-21
      相关资源
      最近更新 更多