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

使用Python+Selenium爬取网页时出现AttributeError问题求助

解决Selenium爬取Audible时的AttributeError问题

错误原因

你代码里的product变量是通过find_elements方法获取的元素列表,而find_element是单个WebElement对象的专属方法,列表类型没有这个属性,因此触发AttributeError。

修正方案

需要遍历product列表中的每个商品元素,逐个提取标题、作者、时长信息,同时修复xpath里多余的转义符,并补充缺失的pandas导入:

修正后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By
import pandas as pd

website='https://www.audible.com/search'
driver=webdriver.Chrome()
driver.get(website)
driver.maximize_window()

container=driver.find_element(By.CLASS_NAME,'adbl-impression-container')
# 修复xpath的转义符,find_elements返回元素列表
products=container.find_elements(by='xpath', value='.//li[contains(@class, "productListItem")]')

book_title=[]
book_author=[]
book_length=[]

# 遍历每个商品元素,逐个提取信息
for product in products:
    title = product.find_element(by='xpath', value='.//h3[contains(@class,"bc-heading")]').text
    author = product.find_element(by='xpath', value='.//li[contains(@class,"authorLabel")]').text
    length = product.find_element(by='xpath', value='.//li[contains(@class,"runtimeLabel")]').text
    
    book_title.append(title)
    book_author.append(author)
    book_length.append(length)

driver.quit()

df=pd.DataFrame({'Title':book_title,'Author':book_author, 'Runtime':book_length})
df.to_csv('audible_data.csv',index=False)
print(df)

关键修正点

  • 将product变量名改为products(语义更清晰),通过循环遍历列表处理每个商品元素
  • 移除xpath表达式中多余的转义符\,避免语法错误
  • 补充import pandas as pd语句(原代码使用了pd但未导入)
  • 对列表中的每个单个元素调用find_element,而非直接对整个列表调用该方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:45:58