使用Selenium提取亚马逊商品价格报错:AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
解决Selenium中AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'的问题
嘿,这个问题我前段时间刚踩过坑!你遇到的这个错误,核心原因是Selenium 4及以上版本已经彻底移除了find_element_by_class_name这类旧的元素定位方法,官方现在推荐使用统一的find_element()方法配合By类来定位元素。
下面是针对你提取亚马逊商品价格需求的完整解决方案:
步骤1:导入必要的依赖
首先要确保导入By类,这是Selenium 4+定位元素的标准方式:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
步骤2:替换旧的定位代码
把原来的driver.find_element_by_class_name("xxx")格式,替换成driver.find_element(By.CLASS_NAME, "xxx")。
针对你提供的亚马逊商品链接,价格元素通常拆分在a-price-whole(整数部分)和a-price-fraction(小数部分)两个节点里,这里推荐用显式等待来确保元素加载完成,避免动态页面加载导致的定位失败:
# 初始化Chrome浏览器(也可替换为Firefox等其他浏览器) options = webdriver.ChromeOptions() # 自定义User-Agent,避免被亚马逊反爬机制识别 options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36") driver = webdriver.Chrome(options=options) # 打开目标商品页面 driver.get("https://www.amazon.com/dp/B01N7GO468/ref=syn_sd_onsite_desktop_217?psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyOTE3T1VVUk5UOVBXJmVuY3J5cHRlZElkPUEwNjg4MzM2MkZJUEJXTU1NT1FBQiZlbmNyeXB0ZWRBZElkPUEwMjQ2NzE1MUVQNEU3Tkk5VjJROSZ3aWRnZXROYW1lPXNkX29uc2l0ZV9kZXNrdG9wJmFjdGlvbj1jbGlja1JlZGlyZWN0JmRvTm90TG9nQ2xpY2s9dHJ1ZQ==") try: # 显式等待价格整数部分加载,最多等待10秒 price_whole = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "a-price-whole")) ) # 定位价格小数部分 price_fraction = driver.find_element(By.CLASS_NAME, "a-price-fraction") # 拼接完整价格 full_price = f"{price_whole.text}.{price_fraction.text}" print(f"当前商品价格:${full_price}") except Exception as e: print(f"提取价格时出错:{str(e)}") finally: # 关闭浏览器 driver.quit()
额外注意事项
- 如果
a-price-whole定位失败,可以尝试用By.ID定位priceblock_ourprice(亚马逊商品价格的常用固定ID),或者右键检查页面元素,确认当前页面的价格节点class/ID是否有变动。 - 亚马逊反爬机制严格,避免短时间内频繁请求同一页面,必要时可以添加随机等待时间降低被封风险。
内容的提问来源于stack exchange,提问作者Maaz Ali




