You need to enable JavaScript to run this app. 使用Selenium爬取乐天商品价格时出现TypeError: 'NoneType'无len()属性错误
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium爬取乐天商品价格时出现TypeError: 'NoneType'无len()属性错误

报错原因与修正方案
  • 直接触发报错的逻辑错误:driver.get() 只负责控制浏览器导航到目标URL,本身无返回值,执行后默认返回None。你把这个None传给BeautifulSoup作为解析源,lxml解析器在处理输入时会尝试读取对象长度,直接抛出TypeError: object of type 'NoneType' has no len()错误。
  • 代码中存在的其他可预见问题:
    • soup.findAll() 返回匹配到的元素列表,不是单个DOM节点,列表没有.text属性,就算拿到正确的页面源码,这一步也会触发属性不存在的报错
    • 固定sleep(3)的等待逻辑可靠性差,网络波动时目标价格节点未加载完成,会出现取不到内容的情况
    • 代码未做浏览器进程回收,长期运行会残留大量chromedriver进程占用系统资源

修正后可直接运行的代码

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

word = '0735850859699'
driver = webdriver.Chrome('chromedriver.exe')
try:
    driver.get(f"https://www.lotteon.com/p/product/LM{word}")
    # 用显式等待替代固定sleep,确保价格节点加载完成再解析
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CSS_SELECTOR, "div.price"))
    )
    # 读取浏览器渲染完成后的完整页面源码作为解析输入
    rendered_page = driver.page_source
    soup = BeautifulSoup(rendered_page, 'lxml')
    # 用find获取单个匹配节点,提取清洗后的文本
    price_node = soup.find("div", class_="price")
    price_content = price_node.get_text(strip=True) if price_node else "未匹配到价格节点"
    print(price_content)
finally:
    # 执行完成后强制关闭浏览器,释放占用资源
    driver.quit()

额外提示:如果调整代码后仍无法提取价格内容,优先核查目标站点当前的DOM结构,确认价格容器的class属性是否和代码中的选择规则一致,避免站点改版导致的选择器失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 07:36:07