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

Python网页爬取报错‘string indices must be integers’求助

遍历CSV链接抓取文章内容的错误修复与实现

错误原因

string indices must be integers错误的根源是:

  • blogurls = i[1]获取到的是单个链接字符串,并非列表类型
  • 后续for rows in blogurls:会遍历该字符串的每一个字符,rows变成单个字符后,blogurls[rows]试图用字符作为索引访问字符串,自然触发索引类型错误

修正后的完整代码

先确保安装所需依赖:

pip install requests beautifulsoup4
import csv
import requests
from bs4 import BeautifulSoup

# 固定请求头,避免被反爬拦截
headers = {"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0"}

with open('/content/Input.csv', mode='r', encoding='utf-8') as file:
    csv_reader = csv.reader(file)
    # 跳过CSV表头(如果你的第一行是列名,比如"序号""URL",必须执行此步)
    next(csv_reader)
    
    # 遍历每一行,处理链接
    for article_id, row in enumerate(csv_reader, start=1):
        url = row[1].strip()  # 取出第二列的链接,去除首尾空格
        if not url:
            print(f"第{article_id}行链接为空,跳过")
            continue
        
        try:
            # 发送请求获取网页内容
            response = requests.get(url, headers=headers)
            response.raise_for_status()  # 捕获HTTP请求错误(如404、500)
            
            # 解析HTML结构
            soup = BeautifulSoup(response.content, 'html.parser')
            
            # 提取文章核心内容(此处需根据目标网页结构调整,示例为提取所有段落文本)
            # 如果目标网站文章在特定容器,比如<div class="post-content">,可改为:
            # article_text = soup.find('div', class_='post-content').get_text(strip=True, separator='\n')
            article_text = '\n'.join([p.get_text(strip=True) for p in soup.find_all('p')])
            
            # 将内容写入文本文件
            with open(f'article_{article_id}.txt', 'w', encoding='utf-8') as txt_file:
                txt_file.write(article_text)
            
            print(f"文章{article_id}抓取完成:{url}")
        
        except Exception as e:
            print(f"文章{article_id}处理失败({url}):{str(e)}")

核心调整说明

  1. 移除无效嵌套循环:直接遍历CSV的每一行,无需对单个链接字符串做二次遍历
  2. 增加表头跳过逻辑:避免把CSV第一行的列名当作链接处理
  3. 错误捕获机制:单个链接处理失败时,程序不会中断,同时输出错误信息便于排查
  4. 编码规范:读写文件时指定utf-8编码,避免中文乱码
  5. 内容提取适配:你需要根据目标网页的HTML结构,修改文章内容提取的代码(注释中有示例)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 22:02:25