首页 > 编程语言 >Python爬虫案例: 跨境电商shopee虾皮指定商品评论采集

Python爬虫案例: 跨境电商shopee虾皮指定商品评论采集

时间:2024-09-06 10:54:21浏览次数:6  
标签:shop product Python self print url shopee 电商 id

前置:

今天分享一个入门级爬虫案例:跨境电商平台虾皮的指定商品评论的采集,对于新手做爬虫练习是一个很不错的选择。如果你是电商工作者也可以利用它节省你宝贵的时间

首先安装好要用的py库,requests用于发送请求,pandas用于做数据处理

pip install requests
pip install pandas

虾皮在商品评论这方面是几乎没有爬虫限制的,所以我们只需要发送请求获取返回结果就好了

你只需要在请求url中拼接好商品id,店铺id,页码(非必须),评论类型(非必须)。

自己想办法开魔法,把控好请求频率和user-agent这些就好了

启动代码后你需要把你想要抓取商品评论的链接给到代码

例如我们想要拿到以下商品的评论,我们就把完整的url复制下来,粘贴到代码里

选择评论类型,并输入页数:

代码会自动从url中利用正则表达式提取出商品id和店铺id去发请求

print("给我一个商品地址")
product_id_url = input()
product_pattern = r"i\.\d+\.(.*?)\?sp_atk"
shop_pattern = r"i\.(.*?)\."
shop_match = re.search(shop_pattern, product_id_url)
product_match = re.search(product_pattern, product_id_url)

接下来等待结果

完成后它会在你的代码所在的文件夹中生成xlsx文件把结果保存在里面,如下图:

代码:

完整代码如下

import requests
import re
import time
import pandas as pd
import json
import os

# 定义一个spider类
class shopee_Spider: 
    # 初始化
    # 定义初始页面url
    def __init__(self,shop_id,product_id,page_num,input_type):
        self.url = 'https://shopee.tw/api/v2/item/get_ratings?exclude_filter=1&filter=0&filter_size=0&flag=1&fold_filter=0&itemid={}&limit=6&offset={}&relevant_reviews=false&request_source=2&shopid={}&tag_filter=&type={}&variation_filters='
        #店铺id
        self.shop_id = shop_id
        #用户选择的商品id
        self.product_id = product_id
        #用户要获取的页数
        self.page_num = page_num
        #用户选择的评论类型
        self.input_type = input_type
        #存储文件名
        self.file_name = 'shopee_remarks.xlsx'
        #提前创建好空的csv文件用于存储
        if not os.path.exists(self.file_name):
            df = pd.DataFrame(columns=['交易号', '商品号', '用户号', '店铺号', '星级','用户名','商品名字','商品图片','客户主观评价','商家回复','地区'])
            df.to_csv(self.file_name, index=False, encoding='utf-8-sig')         



    # 请求函数
    def get_response(self,url):
        headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1'}
        response = requests.get(url, headers=headers,verify=False)
        if response.status_code == 200:
            data = json.loads(response.text)
            self.parse_response(data)
        else:
            print("请求失败,状态码:", response.status_code)
            return response.status_code
        
        
        
    # 解析函数---JSON---数据存储进csv
    def parse_response(self,response_data):
        #创建一个空的容器
        shopee_data = []
        #提取评论中需要的部分
        res_lst = response_data['data']['ratings']
        #循环遍历
        for res_target in res_lst:
            #交易号
            orderid = res_target['orderid']
            #商品号
            itemid = res_target['itemid']
            #用户号
            userid = res_target['userid']
            #店铺号
            shopid = res_target['shopid']
            #星级
            rating_star = res_target['rating_star']
            #用户名
            author_username = res_target['author_username']
            #商品名字
            product_items_name = res_target['product_items'][0]['name']
            ##商品图片
            product_items_image= res_target['product_items'][0]['image']
            #客户主观评价
            user_comment = res_target['comment']
            #商家回复
            if 'ItemRatingReply' in res_target and 'comment' in res_target['ItemRatingReply']:
                Merchant_response = res_target['ItemRatingReply']['comment']
            else:
                Merchant_response = '无'
            #地区
            region= res_target['region']
            
            shopee_data.append([orderid, itemid,  userid, shopid,rating_star,author_username,product_items_name,product_items_image,user_comment,Merchant_response,region])
            
            
        new_data = pd.DataFrame(shopee_data, columns=['交易号', '商品号', '用户号', '店铺号', '星级','用户名','商品名字','商品图片','客户主观评价','商家回复','地区'])
        
        print(new_data)
        
        self.save_data(new_data) 

    #存储函数
    def save_data(self,new_data):
        new_data.to_csv(self.file_name, mode='a', index=False, header=False, encoding='utf-8-sig')
        


    # 主函数
    def run(self):
        offset = 0
        #根据用户输入参数拼接url
        for self.page in  range(1, self.page_num + 1):
            offset = offset + 6
            #拼接生成url
            print(offset)
            if self.input_type in {'0','1','2','3','4','5'}:
                url = self.url.format(str(self.product_id),str(offset),str(self.shop_id),str(self.input_type))
            else:
                return print('请选择类型')
            print(url)
            #启动请求函数
            self.get_response(url)
            time.sleep(1)
            
        print('执行完毕')




# 以脚本方式启动
if __name__ == '__main__':
    # 使用正则表达式提取商品ID
    print("给我一个商品地址")
    product_id_url = input()
    print('\n选择要获取的评论类型(输入对应编码,如:选择五颗星就输入5):\n###########\n#全部评论:        0\n##五颗星:         5\n##四颗星:         4\n##三颗星:         3\n##两颗星:         2\n##一颗星:         1\n')
    input_type = input()
    print("输入您想要获取几页评论:")
    page_num = input()
    product_pattern = r"i\.\d+\.(.*?)\?sp_atk"
    shop_pattern = r"i\.(.*?)\."
    shop_match = re.search(shop_pattern, product_id_url)
    product_match = re.search(product_pattern, product_id_url)
    if shop_match and product_match:
        shop_id = shop_match.group(1)
        product_id = product_match.group(1)
        print("商品id是:" + product_id )
        print("店铺id是:" + shop_id )
        print("------即将获取-----" + page_num+"页------")
        print("准备启动!")
        time.sleep(2)
    elif shop_match is None:
        print("没有找到店铺id,确认商品链接是否正确")
        time.sleep(10)
    elif product_match is None:
        print("没有找到商品id,确认商品链接是否正确")
        time.sleep(10)
    try:
        #传参:id/页数,然后启动爬虫
        spider = shopee_Spider(shop_id,product_id,int(page_num),str(input_type))
        spider.run()
    except Exception as e:
        print("错误:",e)

    print('程序执行完毕')

结论:

经实验,虽然虾皮对评论请求没什么限制,但请求频率过快或是IP不太正常,虾皮平台依旧是会暂时性的封住你的,所以操作时要把控好尺度和分寸

你也可以想办法批量获取商品id及店铺id,做品类级/批量商品的自动化评论收集

标签:shop,product,Python,self,print,url,shopee,电商,id
From: https://blog.csdn.net/m0_59642837/article/details/141952193

相关文章

  • Python正则表达式
    常用方法re.compile(pattern):编译正则表达式模式,返回一个模式对象,用于匹配操作。提高匹配效率,适用于多次匹配的情况。match():从字符串开头开始匹配,只有在字符串的开头匹配成功时,才返回匹配对象。常用于验证字符串是否符合某种模式。search():在字符串中搜索第一个匹配的......
  • python中正则模块
    importre#1.findall()匹配字符串中所有符合正则的字符串,并返回一个列表result_list=re.findall(r"\d+","我的手机号是13812345678,我的QQ号是456789123")print(result_list,type(result_list))#['13812345678','456789123']<class'list&#......
  • 14 Python面向对象编程:反射
    本篇是Python系列教程第14篇,更多内容敬请访问我的Python合集在Python中,“反射”通常指的是根据字符串查找并执行相关的类、方法或者属性的能力。Python提供了几个内置函数和语法特性来支持这种能力,比如getattr(),setattr(),hasattr(),delattr()以及dir()等。这些功能......
  • 15 Python模块
    本篇是Python系列教程第15篇,更多内容敬请访问我的Python合集一个模块其实就是一个文件(以.py结尾)。使用模块的好处是便于维护和重用代码。要创建一个模块,只需编写一个新的文本文件,保存为.py扩展名。1引入模块1.1导入整个模块importmymodulemymodule.some_functi......
  • python 命令行参数解析
    追加参数pythonexample.pyNewYorkLosAngelesChicago给参数申明分配内存Locations:['NewYork','LosAngeles','Chicago']具体实现importargparseparser=argparse.ArgumentParser(description='Processsomelocations.')parser.ad......
  • Python
    Python安装HelloWorldprint("HelloWorld")基础字面量:代码中被写下来固定的值,数字:Number整数int浮点数float复数complex布尔bool字符串:String(双引号)列表:List元组:Tuple集合:Set字典:Dictionary注释单行注释#开头#我是注释print("HelloWorld")......
  • Python开发实例(30)文件搜索工具:创建一个程序,允许用户在指定目录下搜索文件
    创建一个文件搜索工具是一个非常有用的项目,它可以帮助用户在指定目录下查找文件。以下是一个基本的文件搜索工具示例,它使用Python的os库来进行文件搜索。importosdefsearch_files(directory,filename):found_files=[]forroot,_,filesinos.walk(director......
  • Flask:Python轻量级Web框架详解
    Flask是一个用Python编写的轻量级Web应用框架。它被设计为易于使用和扩展,非常适合小型项目和微服务,同时也能够支持大型应用。Flask依赖于少量的外部库,并且提供了一个简单的方式来创建Web应用。Flask的主要特点轻量级:Flask核心非常简单,使得它易于理解和扩展。扩展性:Flask可......
  • Python异步编程:asyncio库详解
    \asyncio是Python的标准库,用于编写单线程的并发代码。它使用async和await语法来定义和调用异步函数,使得I/O密集型程序能够更有效地使用资源。asyncio的主要特点事件循环:asyncio程序由事件循环驱动,它负责调度协程的执行。协程:使用async定义的异步函数被称为协程。任务:asyn......
  • 电商数据API对店群商家有哪些优势
    电商数据API对店群商家而言,具有多方面的显著优势,这些优势能够帮助商家在激烈的市场竞争中脱颖而出,实现更高效、精准的运营和管理。以下是对这些优势的具体阐述:数据实时性与准确性:电商数据API能够直接对接电商平台的数据源,确保商家获取的数据是实时且准确的。这有助于商家......