QaQlinks / Python实例 / 批量提取ASIN标题 131 个条目

批量提取ASIN标题

Python实例 #594 更新 2026-02-10

扫描本地已经保存下来的页面文件,用 BeautifulSoup 提取出 ASIN 和标题,再按成功、失败分到不同文件夹归档。采集跑完一堆 HTML 之后,用它把结果整理成可用的清单,省去逐个打开翻。



import os
import re
import shutil
from bs4 import BeautifulSoup
def extract_data_from_file(filepath: str, success_folder: str):
    with open(filepath, "r", encoding="utf-8", errors="ignore") as f:
        file_content = f.read()
    asin_value = "未找到 currentAsin"
    asin_match = re.search(r'"currentAsin"\s*:\s*"([^"]+)"', file_content)
    if asin_match:
        asin_value = asin_match.group(1)
    else:
        opts_match = re.search(r'var opts\s*=\s*{[^}]*asin\s*:\s*"([^"]+)"', file_content)
        if opts_match:
            asin_value = opts_match.group(1)
    soup = BeautifulSoup(file_content, "html.parser")
    span_element = soup.select_one("h1#title span")
    if span_element:
        span_value = span_element.get_text(strip=True)
    else:
        span_value = "未找到 span 属性值"
    file_name_without_extension = os.path.splitext(os.path.basename(filepath))[0]
    span_value = span_value.replace("'", "\\'")
    success_path = os.path.join(success_folder, os.path.basename(filepath))
    shutil.move(filepath, success_path)
    return file_name_without_extension, asin_value, span_value
def extract_data_from_folder(folder_path: str, success_folder: str):
    results = []
    if not os.path.exists(success_folder):
        os.makedirs(success_folder)
    for filename in os.listdir(folder_path):    
        filepath = os.path.join(folder_path, filename)
        if os.path.isfile(filepath):
            try:
                result = extract_data_from_file(filepath, success_folder)
                results.append(result)
            except Exception as e:
                print(f"无法解析文件: {filename}, 错误: {e}")
    return results
def save_to_csv(results, output_folder, output_csv="result.csv"):
    import csv
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    output_file_path = os.path.join(output_folder, output_csv)
    with open(output_file_path, "w", newline="", encoding="utf-8-sig") as f:
        writer = csv.writer(f)
        writer.writerow(["文件名", "ASIN", "标题"])
        writer.writerows(results)
    print(f"已保存到: {output_file_path}")
if __name__ == "__main__":
    folder_path = r"G:\bulkasin"
    success_folder = r"G:\bulkasin\success"
    output_folder = r"G:\bulkasin\output"
    
    results = extract_data_from_folder(folder_path, success_folder)
    save_to_csv(results, output_folder, "result.csv")


点击统计

最近 30 天 · 单日最高 3 · 数据刚开始累积
3总点击
0今日
3近 7 天
0.1日均
012311-26 · 3 次10-2911-0511-1311-20今天

记录信息

分类
Python实例
类型
Python 脚本
使用
完整说明在原站详情页,可以前往查看
更新
2026-02-10
点击
3 次
编号
#594