python爬虫爬取天猫店铺商品数据

本文介绍了如何使用Python爬虫技术从天猫店铺中爬取商品数据,详细解析了爬虫代码tmmall.py,展示了GitHub上的项目链接,为读者提供了一个实际的爬虫案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!coding=utf-8
import requests
import re
import random
import time
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import pandas as pd
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)  ###禁止提醒SSL警告

class tm(object):####手机端

    def __init__(self,path):  ###保存数据路径
        self.path=path

    def goodsid(self,url):  ###通过店铺URL获取店铺所有ID
        shopname = re.search('https://(.*?).tmall', url).group(1)
        searchurl = 'https://{}.m.tmall.com/shop/shop_auction_search.do?spm=a1z60.7754813.0.0.301755f0pZ1GjU&sort=defaul'.format(
            shopname)
        s=requests.session()
        headers = {'Accept': '*/*',
                   'Accept-Language': 'zh-CN',
                   'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) FxiOS/10.6b8836 Mobile/14G60 Safari/603.3.8',
                   'Referer':'https://{}.m.tmall.com/shop/shop_auction_search.htm?spm=a1z60.7754813.0.0.301755f0pZ1GjU&sort=default'.format(shopname)
                   }
        s.headers.update(headers)
        page1=s.get(url=searchurl,verify=False).text
        print(page1)
        js=json.loads(page1)
        total_page=int(js['total_page'])
        shop_id=js['shop_id']
        shop_title = js['shop_title']
        shop_id_list = []
        shop_title_list = []

        item_id=re.findall('"item_id":(.*?),"',page1)
        title=re.findall('"title":"(.*?)","',page1)
        sold=re.findall('"sold":"(.*?)","',page1)
        totalSoldQuantity=re.findall('"totalSoldQuantity":(.*?),"',page1)
        skuurl=re.findall('"url":"(.*?)","',page1)
        price=re.findall('"price":"(.*?)","',page1)
        item_id_l=len(item_id)
        shop_id_list.append(shop_id)
        shop_id_list.extend(shop_id_list*(int(item_id_l)-1))
        shop_title_list.append(shop_title)
        shop_title_list.extend(shop_title_list*(int(item_id_l)-1))
        # print(js)
        # print(len(shop_id_list))
        # print(len(shop_title_list))
        # print(len(item_id))
        # print(len(title))
        # print(len(sold))
        # print(len(totalSoldQuantity))
        # print(len(skuurl))
        # print(len(price))


        data = {'shop_id': shop_id_list,'shop_title': shop_title_list,'item_id': item_id, 'title': title, 'sold':sold, 'totalSoldQu
### 使用 Python 编写爬虫抓取天猫商品评论数据 为了实现这一目标,可以采用两种主要方法:一种是直接解析网页 HTML 来获取所需的数据;另一种则是利用官方提供的 API 接口。鉴于天猫提供了专门用于访问商品评论的 API,推荐优先考虑后者。 #### 方法一:调用天猫商品评论数据接口 通过调用天猫提供的商品评论数据接口能够更高效地获得结构化的 JSON 数据,减少开发难度并提高效率。具体流程如下: - 需要先注册成为开发者账号,并申请相应的权限以便于合法使用此服务[^2]。 ```python import requests def get_tmall_comments(product_id, page=1): url = f"https://api.tmall.com/comment?product_id={product_id}&page={page}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', # 如果有其他必要的请求头参数也应在此处补充 } response = requests.get(url=url, headers=headers) data = response.json() comments = [] if "comments" in data and isinstance(data["comments"], list): for item in data['comments']: comment_info = { 'content': item.get('content'), 'date': item.get('created_at') } comments.append(comment_info) return comments ``` 这种方法依赖于天猫平台所提供的开放接口文档说明来进行编码工作,在实际应用过程中可能还需要处理分页逻辑以及错误异常情况等细节问题。 #### 方法二:基于 Selenium 的 Web 页面自动化交互方式 如果无法直接使用 API 或者希望模拟真实用户的浏览行为,则可以选择借助浏览器驱动工具如Selenium来完成页面加载后的动态内容读取任务。这种方式虽然相对复杂一些,但对于某些特殊场景下的需求来说更为灵活多变。 ```python from selenium import webdriver from time import sleep options = webdriver.ChromeOptions() options.add_argument('--headless') # 设置无界面模式运行Chrome浏览器实例 driver = webdriver.Chrome(options=options) def fetch_product_reviews_by_selenium(product_url): driver.get(product_url) sleep(3) # 等待页面完全渲染完毕 review_elements = driver.find_elements_by_css_selector('.tm-rate-list .rate-content') reviews_text = [element.text.strip() for element in review_elements] return reviews_text if __name__ == '__main__': product_link = input("请输入想要抓取评论的商品链接:") fetched_reviews = fetch_product_reviews_by_selenium(product_link) print(fetched_reviews[:5]) # 输出前五个评价作为示例展示 ``` 需要注意的是,当采取第二种方案时,应当遵循网站的服务条款规定,合理控制请求频率以免给服务器带来过重负担或触发反爬机制而被封禁IP地址等问题的发生。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值