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

如何从TXT提取HTML内容并存入CSV?代码仅导出最后一行求解

问题解决:提取所有商品条目而非仅最后一条

你的代码只提取最后一条数据的原因是:分别循环所有图片、标题、链接和价格元素时,每次循环都会覆盖变量值,最终仅保留最后一个元素的信息,且只向dataset添加了一次条目。正确的做法是以每个商品的父容器(.grid-item)为单位循环,从每个容器内提取对应数据,从而捕获所有商品条目。

修正后的代码

import pandas as pd
from bs4 import BeautifulSoup

baseurl = 'https://www.soxboxmtl.com'
dataset = []

# 读取TXT中的HTML内容
with open(r'/run/user/759001103/gvfs/smb-share:server=192.168.0.112,share=corporate%20share/Corporate Share/Systems and Infrastructure/Engineering/jbot tests/soxboxmtl2.txt', "r") as f:
    soup = BeautifulSoup(f.read(), "html.parser")
    
    # 遍历每个商品的父容器
    for item in soup.find_all('div', class_='grid-item'):
        # 从当前容器内提取主图的data-src
        img_tag = item.find('img', class_='grid-item-image')
        img_src = img_tag['data-src'] if img_tag else ''
        
        # 提取商品标题并清理多余空格
        title_tag = item.find('div', class_='grid-title')
        title = title_tag.text.strip() if title_tag else ''
        
        # 拼接完整商品链接
        link_tag = item.find('a', class_='grid-item-link')
        full_link = baseurl + link_tag['href'] if link_tag else ''
        
        # 提取商品价格并清理格式
        price_tag = item.find('div', class_='product-price')
        price = price_tag.text.strip() if price_tag else ''
        
        # 将当前商品数据添加到数据集
        dataset.append({
            'Field_01': img_src,
            'Field_02': title,
            'Field_03': full_link,
            'Field_04': price
        })

# 导出到CSV文件
df = pd.DataFrame(dataset).to_csv(r'/run/user/759001103/gvfs/smb-share:server=192.168.0.112,share=corporate%20share/Corporate Share/Systems and Infrastructure/Engineering/jbot tests/soxboxmtl2.csv', index=False)
print(f"共提取{len(dataset)}条商品数据")

关键修复说明

  • 按商品容器循环:通过soup.find_all('div', class_='grid-item')获取所有商品的父容器,确保每个循环处理一个完整的商品条目,避免跨商品数据混淆。
  • 容器内精准查找:使用item.find()替代全局查找,仅从当前商品容器内定位元素,保证数据对应关系正确。
  • 异常防护:添加if xx else ''判断,防止部分商品缺失元素时抛出运行时错误。
  • 数据清理:用.strip()去除标题、价格中的多余空格和换行符,保证输出格式整洁。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 00:35:16