Selenium爬取Goodreads评论报错:TypeError:列表索引应为整数而非WebElement
解决Selenium爬取Goodreads评论时的TypeError问题
错误原因
你的循环逻辑存在错误:for x in more_buttons 中,x本身就是列表内的WebElement对象,而非索引值。但你却用more_buttons[x]去访问列表,这就触发了TypeError——列表索引只能是整数或切片,不能是WebElement对象。
修正后的代码
import time 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 driver.get("https://www.goodreads.com/book/show/36320.Tales_of_the_Cthulhu_Mythos") # 显式等待按钮加载,避免因页面未加载完全找不到元素 wait = WebDriverWait(driver, 10) # 更精准定位"Show more"按钮,避免误操作其他同类别按钮 more_buttons = wait.until(EC.presence_of_all_elements_located( (By.XPATH, "//button[contains(@class, 'Button__labelItem') and contains(text(), 'Show more')]") )) # 循环处理每个按钮 for button in more_buttons: try: if button.is_displayed(): # 用execute_script点击,规避元素被遮挡无法点击的问题 driver.execute_script("arguments[0].click();", button) time.sleep(1) except Exception as e: print(f"处理按钮时出错: {e}") page_source = driver.page_source
额外优化说明
- 精准定位:原代码用
By.CLASS_NAME定位的Button__labelItem可能对应页面多个按钮,用XPath筛选含"Show more"文本的按钮,能避免误操作无关按钮。 - 显式等待:替换直接获取元素的方式,用
WebDriverWait等待元素加载完成,减少页面加载延迟导致的元素缺失问题。 - 异常捕获:添加try-except块,避免单个按钮处理失败导致整个程序崩溃。
内容的提问来源于stack exchange,提问作者EvitaSchaap
相关产品推荐
相关产品推荐

