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

使用Selenium/BS4无法正确定位目标href链接的技术问题求助

金融数据爬虫问题解决方案

一、链接匹配错误修复

问题原因

  1. 正则匹配规则不精准:目标链接中witan-investment-trust与factsheet之间是下划线_分隔,但原正则写的是横杠-,所以只能匹配到旧版横杠分隔的6月报告链接
  2. 直接取匹配结果的第0项:默认返回的匹配列表按页面DOM顺序排列,旧报告排在列表前位,因此拿到的是最早的非目标结果

修复方案

调整正则规则,精准匹配目标日期/分隔符,代码修改如下:

import re
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

# Set options for selenium
options = Options()
options.headless = True
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument("--window-size=1920,1200")

# Requests website using Selenium & ChromeDriver
driver = webdriver.Chrome('C:/AnaConda/chromedriver.exe', options=options)
driver.get('https://www.witan.com/investor-information/factsheets/#currentPage=1')
# 加显式等待,确保链接元素加载完成再取源码
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, 'a[href*=".pdf"]')))
html = driver.page_source
driver.quit()

soup = BeautifulSoup(html, "html.parser")
# 方案1:精准匹配目标日期310821
link_finder = soup.find('a', href=re.compile(r'witan-investment-trust.*factsheet.*310821\.pdf'))
# 方案2:如果要取最新的报告,匹配所有后按日期排序取第一个
# all_links = soup.find_all('a', href=re.compile(r'witan-investment-trust.*factsheet.*\.pdf'))
# 提取href中的日期排序即可
print(link_finder['href'])

二、爬取速度优化(替代Selenium方案)

纯BS4爬取失败是因为页面数据为动态加载,直接请求页面返回的是未渲染的空模板,无需使用Selenium模拟浏览器,可以直接抓取后台数据接口,速度提升10倍以上:

import requests

# 调用页面后台事实表数据接口
url = "https://www.witan.com/umbraco/surface/FactSheetSurface/GetFactSheets?pageNumber=1&pageSize=12"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
}
response = requests.get(url, headers=headers)
data = response.json()

# 遍历返回的json数据找目标链接
for item in data['Results']:
    pdf_url = item['DocumentUrl']
    if "310821" in pdf_url:
        print(pdf_url)
        break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:15:03