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

网页Scraping问题:拆分div内元素为列表项并导出CSV

问题解决思路与代码修正

你的问题出在直接获取了div.links的整体文本,导致所有条件文本挤在一起,没有拆分成独立条目。咱们来调整代码,把每个条件单独提取出来,这样生成CSV时就能自然换行展示了。

修改后的完整代码

from bs4 import BeautifulSoup
import requests
import pandas as pd

base_url = "https://www.lyfboat.com/procedures/"
page = requests.get(base_url)
if page.status_code == requests.codes.ok:
    bs = BeautifulSoup(page.text, 'lxml')
    data = { "Department" : [], "Conditions" : [] }
    containers = bs.findAll('div', class_='column-block')
    for department in containers:
        speciality_tag = department.find('a', {'class': 'speciality'})
        if speciality_tag:
            # 获取科室名称并清理空格
            dept_name = speciality_tag.text.strip()
            # 找到当前部门下所有的条件链接标签
            condition_tags = department.find('div', {'class': 'links'}).find_all('a')
            # 遍历每个条件,把科室和条件一一对应添加到列表
            for tag in condition_tags:
                condition_text = tag.text.strip()
                data['Department'].append(dept_name)
                data['Conditions'].append(condition_text)
    
    # 打印查看结构化后的结果
    print(data['Department'])
    print(data['Conditions'])
    
    # 生成CSV文件,自动按行展示每个科室-条件组合
    df = pd.DataFrame(data)
    df.to_csv('medical_departments.csv', index=False, encoding='utf-8')

关键改动说明

  1. 拆分独立条件:不再直接取div.links的整段文本,而是用find_all('a')精准获取每个条件标签,逐个提取文本,让每个条件都成为独立的列表条目。
  2. 一一对应数据结构:每个条件都匹配所属的科室名称,生成的CSV里每行都是「科室 + 单个条件」的组合,完美解决换行展示的需求。
  3. 文本清理:添加.strip()去除文本前后的冗余空格,让最终数据更整洁规范。

如果你的需求是每个科室对应一个条件列表(同一单元格内用分隔符展示所有条件),可以改用这种写法:

# 替换循环内的代码逻辑
dept_name = speciality_tag.text.strip()
condition_list = [tag.text.strip() for tag in department.find('div', {'class': 'links'}).find_all('a')]
data['Department'].append(dept_name)
data['Conditions'].append(', '.join(condition_list))

这种情况下CSV里每个科室对应的条件会用逗号分隔在同一单元格,你可以根据实际需求选择合适的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:27:38