使用Python采集商品数据

发布于:2024-10-15 ⋅ 阅读:(65) ⋅ 点赞:(0)

采集商品数据

一、任务描述

使用Python编写程序,对想要的商品的数据进行采集,同时要求将采集到的商品数据写入与此文件同一路径下,文件名与这个Python文件名称一样。
采集的内容:商品名称、商品链接、商品价格、商品所在地、店铺名称、商品销量、商品月销量

二、下载需要使用的网页文件

请你将需要进行商品数据采集的网页文件下载到本地,然后将下载的文件移动到模拟编写采集程序的Python文件的路径下。

三、下载第三方库

对数据的采集需要使用到Python的第三方库,为了是的我们编写的Python程序可以正常运行需要我们确保在电脑山已经安装了本程序需要使用的第三方库。
下面是我们使用到的第三方库以及在电脑终端的安装方法:

  • bs4 库: pip install beautifulsoup4

除了使用到 bs4 这个第三方库之外,还需要使用到一些Python自带的标准库 csv , os 库。

四、我下载的HTML文件

淘宝搜索的手机后显示的网页的下载文件。对其中我们需要知道的商品数据进行采集。

实现的代码

在代码中,我适当的中文注释。

# 导入需要使用的模块
from bs4 import BeautifulSoup
import csv,os

# 读取HTML文件内容
with open('手机_淘宝搜索.html', 'r', encoding='utf-8') as file:
    html_content = file.read()

# 创建BeautifulSoup对象
soup = BeautifulSoup(html_content, 'html.parser')

# 定义数据列表
data_list_dict = []

# 查找商品信息
items = soup.find_all('a', class_='doubleCardWrapper--BpyYIb1O')
for item in items:
    # 商品名称
    title = item.find('div', class_='title--F6pvp_RZ').get_text(strip=True)

    # 商品链接
    link = item['href']

    # 商品价格
    price_wrapper = item.find('div', class_='priceWrapper--UVzyZFoG')
    price = price_wrapper.find('span', class_='priceInt--j47mhkXk').get_text(strip=True) + '' + price_wrapper.find('span', class_='priceFloat--zPTqSZZJ').get_text(strip=True)

    # 商品所在地
    location = item.find('div', class_='procity--QyzqB59i').get_text(strip=True)

    # 店铺名称
    shop_name = item.find('a', class_='shopName--bg5aFTrf').get_text(strip=True)

    # 商品销量
    sales = item.find('span', class_='realSales--nOat6VGM').get_text(strip=True)

    # 商品月销量(未找到相关数据,暂设为空)
    monthly_sales = ''

    data_list_dict.append({
        '商品名称': title,
        '商品链接': link,
        '商品价格': price,
        '商品所在地': location,
        '店铺名称': shop_name,
        '商品销量': sales,
        '商品月销量': monthly_sales
    })

# 查看数据列表形式
# print(data_list_dict)

# '''打印数据,方法一'''
# for dictz in data_list_dict:
#     # 遍历字典的每一项,对每一项进行符合要求的打印处理
#     for key, value in dictz.items():
#         # 获取字典中的最后一个键的内容
#         last_key = list(dictz.keys())[-1]
#         if key != last_key:
#             print(value, end=",")  # 打印每一项,并用逗号分隔
#         else:
#             print(value)           # 最后一个项,最后不需要加逗号


'''打印数据,方法二'''
# 遍历列表中所有的字典
for my_dict in data_list_dict:
    # 将字典进行翻转,找到第一个键名
    for key in reversed(my_dict):
        last_key = key
        break     # 找到第一个之后,退出循环
    # 遍历字典,打印每一项
    for key, value in my_dict.items():
        if key == last_key:
            print(value)
        else:
            print(value, end=",")


# '''打印数据,方法三'''
# for index, item in enumerate(data_list_dict):
#     values = ', '.join(str(value) for value in item.values())
#     if index < len(data_list_dict) - 1:
#         print(values)
#     else:
#         print(values)


'''将数据保存到CSV文件'''
# 获取当前文件的“路径”以及“文件名称”
current = os.path.dirname(__file__)                 # 获取当前文件所在目录
name = os.path.basename(__file__).split(".")[0]     # 获取当前文件名,并去掉后缀名
csv_path = os.path.join(current, name + ".csv")     # 定义CSV文件路径

# 创建一个CSV文件,并写入表头
with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
    fieldnames = ['商品名称', '商品链接', '商品价格', '商品所在地', '店铺名称', '商品销量', '商品月销量']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()    # 写入表头
    # 写入数据
    for item in data_list_dict:
        writer.writerow(item)


'''打印数据的方法三的简单示例:'''
# list_of_dicts = [
#     {'name': 'apple', 'price': 5},
#     {'name': 'banana', 'price': 3},
#     {'name': 'orange', 'price': 4}
# ]
#
# for index, item in enumerate(list_of_dicts):
#     values = ', '.join(str(value) for value in item.values())
#     if index < len(list_of_dicts) - 1:
#         print(values)
#     else:
#         print(values)

网站公告

今日签到

点亮在社区的每一天
去签到