使用Selenium进行网页爬虫时点击下一页按钮异常问题求助
问题修复方案
你的代码出错主要有两个核心原因:
- 使用了前端框架自动生成的动态class名
Pagination__NextPage-sc-el3mid-4 gSlsBf,这类带sc-前缀的class是CSS-in-JS方案生成的哈希值,页面更新、缓存变化都会导致类名变更,而且页面可能存在多个隐藏的同class元素,会触发定位偏差。 - 仅等待元素可见不足以保证可点击,若按钮不在当前视窗范围内,Selenium点击会误触发视窗内同坐标的其他元素。
具体修改步骤
1. 更换为稳定的元素定位规则
放弃动态class,改用页面结构+固定属性定位,该网站下一页按钮的西语文本为Siguiente,可以通过文本匹配定位,稳定度更高://button[contains(text(),'Siguiente')]
2. 更换等待条件为可点击状态
将visibility_of_element_located替换为element_to_be_clickable,确保按钮可交互后再执行点击操作。
3. 点击前滚动到按钮位置
通过JS将按钮滚动到视窗范围内,避免误点其他元素,同时可以加个短时间的强制等待避免页面渲染抖动。
4. 增加按钮禁用判断
最后一页时下一页按钮为禁用状态,无需继续点击,避免抛出异常。
5. (可选)使用webdriver_manager自动匹配驱动版本
你已经导入了ChromeDriverManager但未使用,替换固定路径的驱动可以避免版本不兼容问题。
修改后的完整代码
from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait import time options = webdriver.ChromeOptions() options.add_argument('--no-sandbox') options.add_argument('--disable-dev-shm-usage') # 可选:添加无头模式后台运行 # options.add_argument('--headless=new') # 自动适配Chrome驱动版本,无需手动指定路径 wd = webdriver.Chrome(ChromeDriverManager().install(), options=options) wd.maximize_window() wd.get("https://www.bumeran.com.pe/empleos-publicacion-menor-a-7-dias.html") def pag_sig(): # 用文本匹配定位下一页按钮,不依赖动态class next_btn_xpath = '//button[contains(text(),"Siguiente")]' # 等待按钮可点击 boton = WebDriverWait(wd,10).until(EC.element_to_be_clickable((By.XPATH, next_btn_xpath))) # 滚动到按钮位置 wd.execute_script("arguments[0].scrollIntoView({block: 'center'});", boton) # 短等待避免页面抖动 time.sleep(0.5) boton.click() # 等待页面加载完成,可选:可以加个等待当前页码更新的逻辑更稳妥 time.sleep(1) page_max=127 for i in range(page_max): # 先判断下一页是否可点击,避免到最后一页报错 try: pag_sig() except Exception as e: print("已到最后一页,爬取结束") break # 爬取结束后关闭驱动 wd.quit()
额外优化建议
如果还是偶尔出现点击偏差,可以将直接点击替换为JS点击,完全规避元素遮挡、视窗问题:
把boton.click()替换为wd.execute_script("arguments[0].click();", boton)
内容的提问来源于stack exchange,提问作者Samantha Guillén
相关产品推荐
相关产品推荐

