使用Python BeautifulSoup爬取指定日期范围内的标题、链接与日期
解决方案
问题原因
- 原代码中对下拉框的select操作无效:requests发送的是静态HTTP请求,不会执行前端交互逻辑,不过目标站点默认加载当月全部数据,不需要额外切换月份
- 分别提取日期、标题、链接的逻辑容易出现索引错位,且直接用range对象做正则匹配不符合语法规则,无法正确筛选日期
- 时间区间判断使用datetime对象直接比较,比字符串匹配的准确率更高,还能自动处理跨月场景
完整实现代码
import requests from bs4 import BeautifulSoup import datetime import re # 请求页面配置 html_link = 'https://www.ksei.co.id/publications/new-securities-registration?setLocale=en-US' # 加UA头避免被站点反爬拦截 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } response = requests.get(html_link, headers=headers) response.encoding = 'utf-8' soup = BeautifulSoup(response.text, 'html.parser') # 计算时间区间 today = datetime.date.today() four_days_ago = today - datetime.timedelta(days=4) result = [] # 遍历所有日期节点 date_nodes = soup.find_all('b', text=re.compile(r'\d{2}\s\w+\s\d{4}')) for date_node in date_nodes: # 转换日期格式为datetime对象用于比较 pub_date_str = date_node.get_text(strip=True) pub_date = datetime.datetime.strptime(pub_date_str, '%d %B %Y').date() # 筛选符合时间区间的内容 if four_days_ago <= pub_date <= today: # 查找当前日期对应的标题 title_node = date_node.find_next('h2', class_='h4 no-margin') title = title_node.get_text(strip=True) if title_node else '无标题' # 查找当前日期对应的下载链接 href_node = date_node.find_next('a', class_='btn btn--primary') href = href_node['href'] if href_node and 'href' in href_node.attrs else '无链接' # 存入结果集 result.append({ '发布日期': pub_date_str, '标题': title, '链接': href }) # 打印输出结果 for item in result: print(f"发布日期:{item['发布日期']}") print(f"标题:{item['标题']}") print(f"链接:{item['链接']}") print('-'*60)
代码说明
- 通过遍历日期节点+
find_next查找关联元素的方式,保证日期、标题、链接一一对应,不会出现索引错位的问题 - 采用datetime对象直接比较的方式做时间筛选,自动适配跨月、跨年的场景,不需要单独处理月份切换
- 增加了异常兼容逻辑,避免部分节点缺失导致代码运行报错
内容的提问来源于stack exchange,提问作者Joyce
相关产品推荐
相关产品推荐

