Selenium爬取wykop.pl遇TimeoutException:翻页按钮定位失败求助
问题排查与解决方案
核心问题分析
你遇到的TimeoutException本质是下一页按钮的定位逻辑有误,加上滚动后的加载时机没处理好,导致Selenium找不到目标元素。
具体修复步骤
修正CSS选择器
原选择器next > a语法错误,next是类名,必须加.前缀。针对wykop.pl的分页结构,正确的选择器应该是:next_page_button_css_selector = "li.next > a"(或者更简洁的
.next > a,前者更精确,避免页面其他同名类干扰)优化滚动后的等待逻辑
滚动到底部后,页面可能还在加载分页元素,直接等待“可点击”可能过早。建议先等待元素可见,再判断是否可点击:# 滚动到底部 driver_chrome.execute_script("window.scrollTo(0, document.body.scrollHeight);") # 先等待元素可见 next_page_element = WebDriverWait(driver_chrome, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, next_page_button_css_selector)) ) # 再等待元素可点击后点击 WebDriverWait(driver_chrome, 10).until(EC.element_to_be_clickable(next_page_element)).click()替换硬等待为显式等待
原代码中的time.sleep(3)不稳定,换成显式等待Cookie按钮出现,提升可靠性:# 替换原time.sleep(3)和Cookie按钮定位代码 content = WebDriverWait(driver_chrome, 10).until( EC.element_to_be_clickable((By.XPATH, cookies_button_xpath)) ) content.click()处理元素遮挡问题
如果按钮被页面元素遮挡(比如悬浮导航栏),可以用JS直接点击绕过:next_page_element = WebDriverWait(driver_chrome, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, next_page_button_css_selector)) ) driver_chrome.execute_script("arguments[0].click();", next_page_element)
完整修改后的代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC website = "https://wykop.pl/hity/roku/strona/1" cookies_button_xpath = '''//button[contains(@class,'qxOn2zvg e1sXLPUy')]''' service_chrome = Service(executable_path=chromepath) options_chrome = webdriver.ChromeOptions() driver_chrome = webdriver.Chrome(service=service_chrome, options=options_chrome) driver_chrome.maximize_window() driver_chrome.get(website) # 显式等待Cookie按钮并点击 content = WebDriverWait(driver_chrome, 10).until( EC.element_to_be_clickable((By.XPATH, cookies_button_xpath)) ) content.click() # 处理广告弹窗 try: close_ad_button = WebDriverWait(driver_chrome, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "button[data-v-6fdb93ea]")) ) close_ad_button.click() except: pass # 滚动到底部并等待分页元素 driver_chrome.execute_script("window.scrollTo(0, document.body.scrollHeight);") next_page_element = WebDriverWait(driver_chrome, 10).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "li.next > a")) ) # 用JS点击避免遮挡问题 driver_chrome.execute_script("arguments[0].click();", next_page_element)
额外建议
- 可以给ChromeOptions添加无头模式、禁用图片加载等参数,提升爬取效率:
options_chrome.add_argument("--headless=new") options_chrome.add_argument("--disable-images") - 如果分页按钮定位还是不稳定,可以直接通过URL拼接实现翻页(比如
strona/1→strona/2),这种方式比模拟点击更可靠。
内容的提问来源于stack exchange,提问作者Kallistusen
相关产品推荐
相关产品推荐

