使用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
相关产品推荐
相关产品推荐

