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

Colab爬虫写入CSV报错:行大小与列数不匹配问题求助

错误原因

csv.writer的writerow()方法要求传入可迭代序列(如列表、元组),序列的每一个元素对应CSV的一列。你代码中直接将字符串类型的p.text传入writerow(),方法会自动将字符串按单个字符拆分,每个字符视为独立的一列,最终行的列数和预设的1列不匹配,触发报错。

修正方案

仅需要修改写入行的代码,把字符串包裹为长度为1的列表即可:

with open('test.csv', 'w', encoding= 'utf8', newline='') as f:
   thewriter = writer(f)
   header = ['itemname']
   thewriter.writerow(header)

   for link in catagorylinks:
     newr = requests.get(link, headers=headers)
     soup = BeautifulSoup(newr.content, 'html.parser')

     for p in soup.find_all('p' , class_='item-name'):
       item = p.text.strip() # 可选操作:清理文本前后的空白、换行符
       print(item)
       thewriter.writerow([item]) # 核心修改:把单个内容放在列表中,保证列数为1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 12:45:05