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

如何修复获取亚马逊商品名称后无法写入CSV的Python代码?

问题修复方案

核心问题分析

你的代码有三个关键问题导致CSV文件无内容:

  1. 缩进错误:获取商品名称、写入CSV的代码不在for循环的缩进块内,循环根本没执行这些逻辑
  2. 文件流提前关闭:csv.writer是在with open(...)块内创建的,块结束后文件自动关闭,后续调用writer.writerow会失败
  3. 字符串处理无效:[name.strip() for name in name]只是生成了新列表,但没赋值给变量,导致返回的商品名称还是带空格的原始文本

修复后的完整代码

import requests
from bs4 import BeautifulSoup
from lxml import etree as et
import time
import random
import csv

header = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
    'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8'
}

bucket_list = ['https://www.amazon.co.uk/Military-Analogue-Waterproof-Tactical-Minimalist/dp/B0B6C7RMQD/']


def get_product_name(dom):
    try:
        name = dom.xpath('//span[@id="productTitle"]/text()')
        # 修复:将处理后的列表赋值给name,再取第一个元素并处理空值
        name = [item.strip() for item in name]
        return name[0] if name else 'Not Available'
    except Exception as e:
        return 'Not Available'


# 修复:将for循环放到with块内,确保文件在写入时保持打开状态
with open('master_data.csv', 'w', newline='', encoding='utf-8') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['product name', 'url'])

    for url in bucket_list:
        response = requests.get(url, headers=header)
        # 新增:检查请求是否成功,避免后续逻辑出错
        if response.status_code != 200:
            print(f"请求失败,状态码:{response.status_code},URL:{url}")
            writer.writerow(['请求失败', url])
            time.sleep(random.randint(2, 5))
            continue
        
        soup = BeautifulSoup(response.content, 'html.parser')
        amazon_dom = et.HTML(str(soup))

        product_name = get_product_name(amazon_dom)

        time.sleep(random.randint(2, 5))

        writer.writerow([product_name, url])
        print(product_name, url)

关键修复点说明

  • 缩进修正:把product_name、writer.writerow等代码缩进,放到for循环的代码块内,确保循环时能执行写入逻辑
  • 文件流管理:将整个爬取和写入逻辑放到with open(...)块内,保证文件在写入过程中始终处于打开状态
  • 字符串处理优化:把列表推导式的结果赋值给name,同时增加判空逻辑,避免空列表取索引报错
  • 增加请求状态检查:判断响应状态码,避免请求失败时后续逻辑出错,同时记录错误信息到CSV

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:45:47