如何在BeautifulSoup中同时提取配对的日期div与对应table元素
实现思路与代码示例
你可以通过两种常用方式实现日期与对应表格的绑定,适配你给出的HTML结构:
方法1:遍历日期节点匹配后续表格
因为每个mon_title日期节点后一定对应一个mon_list表格,直接遍历所有日期节点,再查找节点后第一个符合要求的表格即可,即使两者中间穿插了其他代码也能正常匹配:
# 存储绑定后的结果,可根据你的需求调整存储格式 date_table_pairs = [] # 先提取所有日期容器 date_divs = soup.find_all("div", {"class": "mon_title"}) for date_div in date_divs: # 提取日期文本,strip参数自动去除首尾空白字符 current_date = date_div.get_text(strip=True) # 查找当前日期节点之后第一个class为mon_list的表格 target_table = date_div.find_next("table", {"class": "mon_list"}) if target_table: date_table_pairs.append({ "date": current_date, "table_content": target_table })
方法2:已提取所有表格时反向匹配前序日期
如果你已经提前拿到了所有mon_list表格,可以反过来给每个表格查找前序最近的日期节点:
tables = soup.find_all("table", {"class": "mon_list"}) date_table_pairs = [] for table in tables: # 查找当前表格之前最近的class为mon_title的div date_div = table.find_previous("div", {"class": "mon_title"}) if date_div: current_date = date_div.get_text(strip=True) date_table_pairs.append({ "date": current_date, "table_content": table })
最终date_table_pairs里就是一一绑定后的日期和对应表格数据,你可以根据后续处理需求调整存储结构。
内容的提问来源于stack exchange,提问作者mediocreAsuka
相关产品推荐
相关产品推荐

