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

基于BeautifulSoup获取与<li>标签关联的<h2>日期数据

解决方法:关联<li>与对应上方的<h2>日期

你的核心问题是要把每个<li class="level-item">和它紧挨着的上方<h2>里的日期绑定起来。现有代码的问题在于没有正确关联每个<h2>和它对应的<ul>,而是全局查找ul,导致日期匹配错误。下面是修正后的实现思路和代码:

关键思路

  1. 遍历所有包含日期的<h2>标签
  2. 对每个<h2>,先把日期转换成你需要的mmddyyyy格式
  3. 找到当前<h2>后面紧跟的<ul>(这就是对应这个日期的列表)
  4. 遍历该<ul>下的所有<li class="level-item">,提取所需字段并和日期组合输出

修正后的代码

import re
import locale
from datetime import datetime
from bs4 import BeautifulSoup

# 假设results_table是你已经获取的页面片段的BeautifulSoup对象
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')  # 注意:Windows系统可能需要调整为'en_US'或其他兼容值

# 遍历所有包含月份的h2标签
for h2 in results_table.find_all('h2', string=re.compile('January|February|March|April|May|June|July|August|September|October|November|December')):
    # 处理日期格式:从"May 18, 2018"转为"05182018"
    date_str = h2.get_text(strip=True)
    try:
        date_obj = datetime.strptime(date_str, '%B %d, %Y')
        formatted_date = date_obj.strftime('%m%d%Y')
    except ValueError:
        # 处理可能的日期格式错误,比如缺失逗号或空格
        continue
    
    # 找到当前h2后面紧跟的ul(对应这个日期的列表)
    ul = h2.find_next('ul')
    if not ul:
        continue  # 如果h2后面没有ul,跳过
    
    # 遍历ul下的每个level-item li
    for li in ul.find_all('li', class_='level-item'):
        a_tag = li.find('a')
        if not a_tag:
            continue
        
        # 提取href
        href = a_tag.get('href', '')
        # 提取span里的文本(another value)
        span_text = a_tag.find('span').get_text(strip=True) if a_tag.find('span') else ''
        # 提取a标签里除了span之外的文本(long description)
        a_full_text = a_tag.get_text(strip=True)
        long_desc = a_full_text.replace(span_text, '').strip()
        
        # 组合成你需要的格式并输出
        print(f"{formatted_date},{href},sometext,{span_text},{long_desc}")

代码解释

  • 日期处理:用h2.get_text(strip=True)获取干净的日期字符串,再通过strptime解析、strftime转换格式,加上异常处理避免格式错误导致崩溃。
  • 关联h2和ul:h2.find_next('ul')确保我们只取当前日期对应的列表,而不是页面中所有的ul。
  • 提取li内容:分别从a标签提取href、span提取对应文本,再通过文本替换得到span之外的长描述,保证每个字段准确。

这样运行后,就能输出你期望的每行包含对应日期的格式内容了。

内容的提问来源于stack exchange,提问作者Life is complex

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:29:43