You need to enable JavaScript to run this app. Flask中Selenium爬取商品报NoSuchElementException问题排查
优惠活动
大模型
产品
解决方案
定价
更多

Flask中Selenium爬取商品报NoSuchElementException问题排查

问题根本原因
  • 触发本次报错的直接原因是CSS选择器语法使用错误:原代码中写的多类选择字符串button.c-button-yMKB7 c-button--primary-39fbj c-button--inverted-UZv88 c-button--primary-3tLoH,类名之间仅用空格分隔。按照CSS选择器语法规则,空格代表“后代元素”匹配逻辑,即这段代码实际要查找的是「class为c-button-yMKB7的按钮内部,所有后续层级中带其他类名的子元素」,而非“本身同时携带所有这些类的按钮元素”,从语法层面就无法匹配到位于弹窗层的目标按钮。
  • 定位规则依赖动态变化的类名:John Lewis这类采用现代前端工程化构建的电商站点,组件类名末尾的哈希后缀(如c-button-yMKB7中的yMKB7、c-button--primary-39fbj中的39fbj)是每次前端版本发布时随机生成的,硬编码的完整类名只要站点发版更新就会失效,即使选择器语法写对,运行时也会因为类名变化报元素不存在。
  • 等待逻辑顺序颠倒:原代码在browser.get(website_address)完成页面跳转、固定休眠10秒之后,才调用browser.implicitly_wait(20)设置隐式等待。隐式等待仅对设置完成之后的元素查找操作生效,设置前的页面加载阶段完全没有等待机制兜底,元素未加载完成时就直接发起查找,自然会触发NoSuchElementException。
  • 运行环境版本过旧:从堆栈信息可见,使用的Chrome版本为74、对应Chromedriver版本也为74,属于2019年的旧版本,当前站点前端已经适配现代浏览器标准,旧版浏览器渲染出的DOM结构和线上最新版本存在差异,也会进一步加剧元素定位失败的概率。
可落地的解决方案
  • 修正CSS选择器的匹配逻辑:如果确实需要匹配同时带多个类的元素,每个类名前都需要加.,采用无空格的连写形式,例如按钮同时带多个类的正确写法是button.c-button-yMKB7.c-button--primary-39fbj.c-button--inverted-UZv88.c-button--primary-3tLoH。考虑到动态类名的不稳定性,更推荐放弃依赖带哈希的随机类名,通过元素的固定属性定位:
    • 定位Cookie同意按钮时,直接通过按钮的固定文本匹配,比如用XPath定位//button[normalize-space(text())='Accept All Cookies'],不受类名变化影响
    • 定位搜索提交按钮、价格元素时,用类名的固定片段做模糊匹配,比如button[class*='c-button--primary']、div[class*='c-product-card__price']
  • 调整等待逻辑顺序:把隐式等待的设置移到browser.get()之前,在浏览器初始化完成、发起页面跳转前就配置好全局等待规则。同时优先使用显式等待(WebDriverWait)替代固定时长的time.sleep,针对关键操作节点等待元素可交互后再执行点击、输入操作,适配不同网络环境下的加载速度差异。
  • 替换已废弃的旧版API:原代码使用的find_element_by_css_selector、find_element_by_id等方法是Selenium 3.x的旧接口,目前已被官方标记为废弃,统一改用find_element(by=By.XXX, value=xxx)的标准写法,兼容当前最新版Selenium 4的运行逻辑。
  • 降低自动化被检测概率:补充启动参数options.add_argument('--disable-blink-features=AutomationControlled'),避免站点检测到自动化运行特征后,返回和正常桌面端用户不一致的简化版/移动端DOM结构,导致原本要找的桌面端按钮元素根本不存在。
修正后的核心代码参考
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

def scrape_johnLewis(product_name):
    website_address = 'https://www.johnlewis.com/'
    options = webdriver.ChromeOptions()
    options.add_argument('start-maximized')
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    options.add_argument('--disable-blink-features=AutomationControlled')

    browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    # 提前设置隐式等待
    browser.implicitly_wait(20)
    wait = WebDriverWait(browser, 15)
    browser.get(website_address)

    # 显式等待Cookie按钮可点击,替代固定休眠
    accept_btn = wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept All')]")))
    accept_btn.click()

    # 通过通用特征匹配搜索输入框,不硬依赖mobileSearch的固定id
    search_input = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='search']")))
    search_input.send_keys(product_name)

    # 模糊匹配搜索提交按钮
    search_submit = browser.find_element(By.CSS_SELECTOR, "div.input-with-submit button[class*='c-button']")
    search_submit.click()

    # 等待商品列表加载后,模糊匹配价格元素
    wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div[class*='c-product-card__price']")))
    product_price_raw_list = browser.find_elements(By.XPATH, "//div[contains(@class, 'c-product-card__price')]/span")
    product_price_list = [elem.text for elem in product_price_raw_list]
    print(product_price_list)


if __name__ == "__main__":
    scrape_johnLewis('Canon EOS 90D Digital SLR Body')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.04 09:24:05