无法从Wiley期刊页面提取数据,求排查Selenium代码问题
问题分析与修复方案
核心问题点
- 无头浏览器被反爬检测:默认的headless模式特征明显,会被Wiley的反爬机制识别,导致页面无法正常加载目标内容。
- 未处理Cookie授权弹窗:页面加载后弹出的Cookie同意窗口会阻碍DOM渲染或元素定位,不处理会导致后续操作失败。
- 定位器稳定性不足:依赖DOM层级的XPATH容易因网站结构更新失效,缺乏鲁棒性。
- 等待策略不严谨:固定时长的
time.sleep效率低,且presence_of_element_located仅确保元素存在,无法保证其可见并渲染出文本。
修正后的代码
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 import time def fetch_current_article_data(url_article): options = webdriver.ChromeOptions() # 伪装正常浏览器环境,规避反爬检测 options.add_argument("--headless=new") options.add_argument("--disable-blink-features=AutomationControlled") options.add_argument("--window-size=1920,1080") options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36") options.add_experimental_option("excludeSwitches", ["enable-automation"]) options.add_experimental_option('useAutomationExtension', False) driver = webdriver.Chrome(options=options) # 移除webdriver标识,进一步隐藏自动化痕迹 driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})") try: driver.get(url_article) # 处理Cookie同意弹窗 try: cookie_btn = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, "button#truste-consent-button")) ) cookie_btn.click() time.sleep(1) except: # 无弹窗则跳过 pass # 使用稳定的CSS选择器定位可见的标题元素 article_title_element = WebDriverWait(driver, 20).until( EC.visibility_of_element_located((By.CSS_SELECTOR, "h1.article-title")) ) article_title = article_title_element.text.strip() print("Article Title:", article_title) except Exception as e: print("An error occurred:", e) # 可选:打印页面源码用于排查 # print(driver.page_source) finally: driver.quit() fetch_current_article_data("https://acsjournals.onlinelibrary.wiley.com/doi/full/10.3322/caac.21774")
关键修正说明
- 反爬规避:采用新版无头模式,添加用户代理、窗口尺寸等参数,并移除自动化标识,模拟真实浏览器行为。
- 弹窗处理:针对Wiley的Cookie弹窗增加点击逻辑,确保页面正常渲染。
- 定位器优化:使用基于class属性的CSS选择器,比依赖DOM层级的XPATH更稳定,适配网站结构变更。
- 等待策略升级:用
visibility_of_element_located替代presence_of_element_located,确保元素可见且文本已加载完成。
内容的提问来源于stack exchange,提问作者Irina
相关产品推荐
相关产品推荐

