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

使用Sublime+Selenium+Chrome开发Python爬虫运行报错问题咨询

问题排查&修复方案

你现有代码存在4处会触发报错的问题,逐一修正即可正常运行:

  • 驱动初始化写法不符合新版Selenium规范:你已经导入了Service类但未使用,新版Selenium不支持直接在webdriver.Chrome()中传入驱动路径的旧写法,必须通过Service实例加载驱动。
  • 等待模块导入路径错误:你注释掉的两个等待相关依赖,之前导入报错是因为路径写错,WebDriverWait和expected_conditions实际归属selenium.webdriver.support路径,而非common目录。另外你当前代码未加等待逻辑,浏览器刚打开页面、元素还未渲染完成就执行查找,必然触发元素不存在的报错。
  • CLASS_NAME选择器用法错误:By.CLASS_NAME仅支持传入单个类名,你传入的ng-tns-c210-4 text-promo-1是空格分隔的两个类名,直接使用会触发定位报错,查找同时具备多个类名的元素需要用CSS选择器实现。
  • 代码末尾多余的***属于无意义字符,会触发语法错误,直接删除即可。
修正后可直接运行的完整代码
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
# 修正等待模块的导入路径
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

# 通过Service实例加载Chrome驱动
service = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=service)
driver.get("https://www.royalcaribbean.com/account/cruise-planner/category/pt_beverage/product/3222?bookingId=1429192&shipCode=NV&sailDate=20220907")

# 设置最长10秒的显式等待,等目标元素加载完成后再提取文本,避免元素未加载导致的报错
target_element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, '.ng-tns-c210-4.text-promo-1'))
)
print(target_element.text)

# 运行结束后关闭浏览器
driver.quit()

额外注意:类名ng-tns-c210-4是Angular前端框架自动生成的动态类名,页面刷新后后缀数字大概率会变化,会导致定位失效,日常写定位时优先使用text-promo-1这类业务相关的固定类名,稳定性会高很多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 09:06:21