Selenium Python无限滚动场景点击ShowMore按钮报错求助
问题原因定位
- 终端输出的
Passthrough is not supported, GL is disabled、USB/蓝牙相关报错均属于Chrome浏览器的兼容类警告日志,仅为日志输出,不会中断代码执行,不是导致循环提前break的根因。 - 核心问题1:调用
find_element_by_class_name时传入了多个以点分隔的复合类名,该方法本身不支持多类名匹配,首次能成功定位属于巧合,后续页面加载后元素定位直接失败抛出异常,触发except分支的break逻辑。 - 核心问题2:ActionChains实例仅在初始化阶段创建一次,多次调用
move_to_element、click方法会累积历史动作,执行时会重复执行之前的操作,导致后续点击逻辑失效。 - 核心问题3:全部使用固定时长的sleep做等待,没有做元素加载状态判断,可能出现ShowMore按钮还未渲染完成就执行查找逻辑,直接抛出异常触发break。
可行解决方案
- 替换元素定位方式,使用CSS选择器定位ShowMore按钮,原生支持多类名匹配,定位准确率更高。
- 取消ActionChains动作链操作,改用JS执行点击操作,规避动作链累积问题,稳定性远高于动作链点击。
- 新增显式等待逻辑,等待ShowMore按钮可点击后再执行操作,替代固定时长的sleep,同时减少无意义的等待时间。
- 给Chrome启动参数新增禁用GPU、屏蔽非致命日志的配置,消除无用的报错日志输出。
修改后可运行代码
from selenium import webdriver from time import sleep from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.chrome.options import Options import pandas as pd options = Options() # 禁用GPU、屏蔽非致命错误日志 options.add_argument('--disable-gpu') options.add_argument('--log-level=3') options.add_experimental_option('excludeSwitches', ['enable-logging']) driver = webdriver.Chrome('D:\chromedriver', chrome_options = options) driver.maximize_window() # 打开谷歌Play评论页 driver.get("https://play.google.com/store/apps/details?id=com.mobile.legends&showAllReviews=true") sleep(5) last_height = driver.execute_script("return document.body.scrollHeight") SCROLL_PAUSE_TIME = 5 click = 0 MAX_CLICK = 100 while click < MAX_CLICK: # 滚动到页面底部 driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") sleep(SCROLL_PAUSE_TIME) new_height = driver.execute_script("return document.body.scrollHeight") # 滚动高度无变化,尝试点击ShowMore if new_height == last_height: try: # 显式等待按钮可点击,最多等待10秒 showMore = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, ".U26fgb.O0WRkf.oG5Srb.C0oVfc.n9lfJ.M9Bg4d")) ) # 用JS点击,稳定性更高 driver.execute_script("arguments[0].click();", showMore) sleep(7) print(f"Click Showmore {click}") click += 1 except Exception as e: print("------Scroll Finish-------") print(f"Click ShowMore Counts = {click}") break last_height = new_height # 后续爬取评论逻辑可自行补充
内容的提问来源于stack exchange,提问作者NF4Caniago
相关产品推荐
相关产品推荐

