You need to enable JavaScript to run this app. Python Selenium爬取WIPO专利多页时循环失效、元素过期异常问题
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium爬取WIPO专利多页时循环失效、元素过期异常问题

核心问题定位
  • 抓取内容重复根因:翻页操作触发后没有校验页面是否真正加载完成,立刻抓取元素时拿到的还是上一页未刷新的DOM内容;原代码主循环每次执行都通过PCT=driver.getPCT()覆盖之前的存储结果,没有做增量数据合并;循环结束后额外多调用了一次翻页接口,没有对应抓取动作。
  • StaleElementReferenceException触发逻辑:WIPO站点是JSF动态渲染架构,每次翻页会全量替换表格、翻页按钮对应的DOM节点,之前缓存的元素引用会直接失效;原代码使用固定sleep()等待页面加载,受网络波动影响,无法精准对齐页面渲染完成时机,元素定位时刚好碰到DOM重绘阶段就会抛出异常;异常触发页码不固定,本质是等待时间和实际加载速度错位导致的。
  • 爬取循环提前中断根因:主循环使用的计数变量i没有初始化,第一次执行循环判断就会触发未定义变量报错,中断次数完全随机,和实际翻页进度无关。
优化方案

核心调整规则

  • 用显式等待替代固定sleep(),所有元素定位、翻页操作前必须校验目标元素处于可交互、稳定存在的状态,从根源消除元素引用过期问题
  • 翻页后必须校验页面显示的当前页码和预期匹配,确认跳转完成后再开始抓取,杜绝重复抓取上一页内容
  • 抓取数据做增量追加存储,不使用覆盖式赋值
  • 翻页操作增加异常重试逻辑,遇到元素引用失效时自动重新定位目标按钮,不需要中断整个爬取流程

优化后可直接运行的代码

import os
from time import sleep
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
from selenium.common.exceptions import StaleElementReferenceException, TimeoutException

class autoScraper():
    def __init__(self, ep="./chromedriver", headless=False):
        options = webdriver.ChromeOptions()
        if headless:
            options.add_argument("--headless")
        options.add_argument("--start-maximized")
        # 规避站点自动化检测
        options.add_experimental_option("excludeSwitches", ["enable-automation"])
        options.add_experimental_option('useAutomationExtension', False)
        self.driver = webdriver.Chrome(executable_path=ep, options=options)
        self.wait = WebDriverWait(self.driver, 15, poll_frequency=0.5)

    def closeDriver(self):
        self.driver.close()
    
    def connector(self, a="https://patentscope.wipo.int/search/en/search.jsf"):
        success = False
        try:
            self.driver.get(a)
            # 等待初始搜索按钮可点击后再执行操作
            search_btn = self.wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[5]/div/div[2]/form/div/div[1]/div[2]/div/div/div[1]/div[2]/button')))
            search_btn.click()
            # 等待结果页基础元素加载完成
            self.wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, 'select[id*="rpp"]')))
            # 选择每页展示200条数据
            rpp_select = self.driver.find_element(By.XPATH, '/html/body/div[2]/div[4]/div/div[1]/div[2]/div/form[1]/div/div[1]/div[2]/div/select[1]')
            rpp_select.click()
            self.wait.until(EC.element_to_be_clickable((By.XPATH, '/html/body/div[2]/div[4]/div/div[1]/div[2]/div/form[1]/div/div[1]/div[2]/div/select[1]/option[4]'))).click()
            success = True     
        except Exception as e:
            print(f"初始化流程报错: {str(e)}")
        return success

    def getPCT(self):
        PCT = []
        row_xpath = '/html/body/div[2]/div[4]/div/div[1]/div[2]/div/form[2]/div/div[1]/div/div/table/tbody/tr'
        # 等待表格所有行渲染完成
        self.wait.until(EC.presence_of_all_elements_located((By.XPATH, row_xpath)))
        rows = self.driver.find_elements(By.XPATH, row_xpath)
        # 逐行提取申请号,取消硬编码200次的循环逻辑
        for row in rows:
            try:
                app_no = row.find_element(By.XPATH, './/div/div[2]/div/div[1]/span[2]/span[2]').text
                PCT.append(app_no)
            except:
                continue
        return PCT   

    def clickNextPage(self, target_page_num):
        # 元素失效时自动重试3次
        retry_count = 0
        while retry_count < 3:
            try:
                next_btn = self.wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[title="Next Page"]')))
                next_btn.click()
                # 等待页码标识更新为目标页码,确认翻页成功
                self.wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, 'span[id*="pageStatus"]'), f"Page {target_page_num}"))
                return True
            except StaleElementReferenceException:
                retry_count +=1
                sleep(0.5)
            except TimeoutException:
                retry_count +=1
                sleep(1)
        raise Exception("连续3次尝试翻页失败")

if __name__ == '__main__':
    all_pct = []
    driver = autoScraper()
    max_target_page = 100
    if driver.connector():
        sleep(5)
        for current_page in range(1, max_target_page+1):
            # 抓取当前页内容,增量追加到总列表
            page_pct = driver.getPCT()
            all_pct.extend(page_pct)
            print(f"已完成第{current_page}页抓取,累计获取{len(all_pct)}条申请号")
            # 未到目标页时执行翻页
            if current_page < max_target_page:
                driver.clickNextPage(current_page+1)
    print(f"爬取完成,共获取申请号总数: {len(all_pct)}")
    # 结果存储
    os.makedirs("./download/", exist_ok=True)
    with open('./download/pct.txt','w', encoding='utf-8') as f:
        for line in all_pct:
            f.write(line+'\n')
    print("爬取结果已写入./download/pct.txt")
    driver.closeDriver()
运行注意事项
  • 禁止使用固定时长sleep()替代页面状态校验,所有等待动作必须绑定实际DOM元素的状态,从根源规避元素引用过期异常
  • 翻页时必须校验页码标识和预期匹配,防止因页面加载延迟导致抓取到重复的上一页内容
  • 元素定位优先使用属性匹配、相对路径,减少依赖绝对xpath的定位逻辑,降低DOM结构变动带来的定位失败概率

内容的提问来源于stack exchange,提问作者user14850031

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.12 18:45:03