You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Selenium的find_element()方法获取div类中的文本

Selenium滚动后无法获取div内容的问题

问题背景

页面滚动功能正常,但无法获取并打印class为description的div内部内容。

初始代码

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service


s=Service('D:\enviroments\casino\chromedriver.exe')
driver = webdriver.Chrome(service=s)
url='https://www.casinoimportaciones.com.uy/accesorios-escola'
driver.get(url)

time.sleep(5)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")

while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

    # Wait to load page
    time.sleep(5)

    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")
    if new_height == last_height:
        driver.execute_script("window.scrollTo(0,-250);")
        time.sleep(10)
        elem2=driver.find_element(By.CLASS_NAME,"//div[@class='description']")
        
        print(elem2)
        time.sleep(100)
    else:
        last_height = new_height

初始报错

执行代码后抛出InvalidArgumentException,原因是使用By.CLASS_NAME定位时,传入了XPath格式的字符串,而By.CLASS_NAME仅接受纯类名字符串。

更新后的问题

修复元素定位方式后,打印结果为元素对象(如<selenium.webdriver.remote.webelement.WebElement (session="xxx", element="xxx")>),而非div内部的文本内容。

解决方案

1. 修正元素定位方式

二选一即可:

  • 使用By.CLASS_NAME,仅传入类名:
    elem2 = driver.find_element(By.CLASS_NAME, "description")
    
  • 使用By.XPATH,传入完整XPath表达式:
    elem2 = driver.find_element(By.XPATH, "//div[@class='description']")
    

2. 获取并打印元素文本

直接打印元素对象只会输出内存信息,需调用text属性或get_attribute("textContent")获取文本:

# 获取单个元素文本
print(elem2.text)

# 若页面存在多个class为description的div,用find_elements遍历获取所有文本
elements = driver.find_elements(By.CLASS_NAME, "description")
for elem in elements:
    print(elem.text)

3. 优化等待方式(可选)

避免固定time.sleep(),改用Selenium显式等待提升代码稳定性:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待元素加载完成后再获取
elements = WebDriverWait(driver, 10).until(
    EC.presence_of_all_elements_located((By.CLASS_NAME, "description"))
)

内容的提问来源于stack exchange,提问作者gmyb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 06:42:40