You need to enable JavaScript to run this app. 如何用BeautifulSoup批量爬取多URL数据并统一存储为CSV文件
优惠活动
大模型
产品
解决方案
定价
更多

如何用BeautifulSoup批量爬取多URL数据并统一存储为CSV文件

多URL批量爬取并写入CSV的实现方案

问题本质定位

你当前代码仅能获取最后一个URL响应内容的核心原因是:在遍历URL的循环逻辑中,用于存储para、para_2的变量被每次循环的结果覆盖,没有把每轮爬取的结果单独留存并写入文件,最终变量中只剩最后一次循环的赋值内容。

实现逻辑拆解

  • 提前在循环外初始化CSV文件写入对象,设置好表头,循环过程中逐行追加内容,避免重复打开文件时清空原有内容
  • 将单个URL的解析逻辑做成独立的处理步骤,每轮循环单独返回当前URL对应的para、para_2结果,避免临时变量被反复覆盖
  • 增加基础异常兜底,单个URL请求失败、目标DOM节点不存在时,对应行填写空值,不中断整体批量爬取流程

可直接适配的核心代码

import csv
import requests
from bs4 import BeautifulSoup

# 初始化输出CSV,newline参数用于避免Windows环境下写入出现多余空行
with open('crawl_result.csv', 'w', newline='', encoding='utf-8-sig') as csv_file:
    csv_writer = csv.writer(csv_file)
    # 写入表头,对应要求的Text、Time列
    csv_writer.writerow(['Text', 'Time'])

    # 替换为你原本从ALL_NUMBERS.txt读取数值、拼接URL的逻辑
    with open('ALL_NUMBERS.txt', 'r', encoding='utf-8') as num_source:
        num_list = [line.strip() for line in num_source if line.strip()]
    # 替换为你的实际URL拼接模板
    url_template = "https://你的目标站点路径/{}"
    target_urls = [url_template.format(num) for num in num_list]

    # 遍历全量URL逐个爬取
    for url in target_urls:
        para_content = ""
        para2_content = ""
        try:
            # 发请求获取页面内容
            page_resp = requests.get(url, timeout=10)
            page_resp.encoding = page_resp.apparent_encoding
            soup = BeautifulSoup(page_resp.text, 'html.parser')

            # 提取div.WYSIWYG articlePage下所有p标签的内容
            article_block = soup.select_one('div.WYSIWYG.articlePage')
            if article_block:
                all_p = article_block.find_all('p')
                para_content = "\n".join([p.get_text(strip=True) for p in all_p])
            
            # 提取div.contentSectionDetails下所有span标签的内容
            detail_block = soup.select_one('div.contentSectionDetails')
            if detail_block:
                all_span = detail_block.find_all('span')
                para2_content = " ".join([span.get_text(strip=True) for span in all_span])

        except Exception as e:
            print(f"当前URL爬取失败:{url},错误信息:{str(e)}")
        
        # 将当前URL的两组结果逐行写入CSV,不会覆盖之前的内容
        csv_writer.writerow([para_content, para2_content])

新手避坑提醒

  • 不要在循环内部用w模式反复打开同一个CSV文件写入,这种操作每次打开都会清空文件原有内容,最终只会留存最后一次写入的结果
  • 提取多标签文本时,要将所有匹配到的标签内容用指定分隔符(换行/空格)拼接为完整字符串再写入,否则会出现单元格内容截断的问题
  • 批量爬取时可在请求间增加1-2秒的间隔,避免短时间高频请求被目标站点拦截

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 19:15:02