You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python Selenium点击页面链接后抓取内容仍为旧数据如何解决?

问题原因

  • 你使用的绝对XPath路径定位元素可靠性极低,经核对目标页面结构,「Popular」标签对应列表第1个li节点,「New」标签对应列表第2个li节点,你代码中选中的li[1]实际上仍然是「Popular」标签,所以点击后内容没有发生变化
  • 固定时长的time.sleep兼容性差,即使延长等待时间也无法保证异步内容完全渲染完成,容易出现提前读取页面源码的情况

修复方案

优先使用文本特征定位标签,搭配Selenium显式等待判断内容加载状态,修正后代码如下:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.homeworkmarket.com/fields/business-finance")
wait = WebDriverWait(driver, 15)
# 通过文本匹配定位New标签,稳定性远高于绝对路径
new_tab = wait.until(EC.element_to_be_clickable((By.XPATH, '//a[text()="New"]')))
new_tab.click()
# 等待New分类下的内容节点加载完成后再读取源码
wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'css-e5w42e')))
page = driver.page_source
soup = BeautifulSoup(page, 'html.parser')

原有抓取链接的代码无需修改,直接复用即可:

question_links = soup.find_all(class_='css-e5w42e')
final_links = []
for link in question_links:
    if 'href' in link.attrs:
        link = 'https://www.homeworkmarket.com' + str(link.attrs['href'])
        print(link)
        final_links.append(link)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 05:15:01