Python爬虫天猫店铺全部商品一记

简介: 1、前言最近小姐姐工作需要,需要爬取天猫某店的全部商品,正好小哥学习了Python几个月,就答应上手试试!结果第一道题就难住了,天猫登陆需要账号密码和验证码!!!虽然知道可以通过模拟和Session操作,但是,始终是新手开车,还没有学习那么高深,感觉...

1、前言

最近小姐姐工作需要,需要爬取天猫某店的全部商品,正好小哥学习了Python几个月,就答应上手试试!结果第一道题就难住了,天猫登陆需要账号密码和验证码!!!虽然知道可以通过模拟和Session操作,但是,始终是新手开车,还没有学习那么高深,感觉会走很多弯路!!另外,也想想,有没有什么更简单的方法???

不出意思,还真发现啦!天猫的手机版可以不用登陆,全部数据访问!!!就这样~

开始吧!

2、遇到的坑点

本文主要是在 利用Python爬虫爬取指定天猫店铺全店商品信息 - 晴空行 - 博客园 这个大哥的基础上,踩坑填坑,然后增加自己一些数据要求~

  • 坑一
File "/Users/HTC/Documents/Programing/Python/WebCrawlerExample/WebCrawler/Tmall_demo.py", line 63, in get_products
    writer.writerows(products)
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 158, in writerows
    return self.writer.writerows(map(self._dict_to_list, rowdicts))
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 151, in _dict_to_list
    + ", ".join([repr(x) for x in wrong_fields]))
ValueError: dict contains fields not in fieldnames: 'titleUnderIconList'

writer.writerows 没有找到这个'titleUnderIconList'字段,这个字段应该是天猫的接口后来返回的数据,在代码里只能删除掉:

del product['titleUnderIconList']del product['titleUnderIconList']
  • 坑二
File "/Users/HTC/Documents/Programing/Python/WebCrawlerExample/WebCrawler/Tmall_demo.py", line 65, in get_products
    writer.writerows(products)
  File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/csv.py", line 158, in writerows
    return self.writer.writerows(map(self._dict_to_list, rowdicts))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 26-27: ordinal not in range(128)

熟悉的人儿,看到python3与python2的区别,就知道,'ascii' codec can't encode 就是编码问题,问题就出来这里writer.writerows, python3处理、解析或转换和保存时,最好都指定一下使用 utf-8编码吧,特别是遇到中文的情况!

最后指定编码用utf-8:

with open(self.filename, 'a', encoding="utf-8", newline='') as f:
    writer = csv.DictWriter(f, fieldnames=title)
    writer.writerows(products)
  • 坑三
035009803B0
图片下载错误 : http//img.alicdn.com/bao/uploaded/i4/821705368/TB1Sht8cfQs8KJjSZFEXXc9RpXa_!!0-item_pic.jpg Invalid URL '035009803B0': No schema supplied. Perhaps you meant http://035009803B0?
02100713003
图片下载错误 : http//img.alicdn.com/bao/uploaded/i1/821705368/TB1_OIkXQfb_uJkSmRyXXbWxVXa_!!0-item_pic.jpg Invalid URL '02100713003': No schema supplied. Perhaps you meant http://02100713003?
02800614023
图片下载错误 : http//img.alicdn.com/bao/uploaded/i3/821705368/TB1kKK6cInI8KJjSsziXXb8QpXa_!!0-item_pic.jpg Invalid URL '02800614023': No schema supplied. Perhaps you meant http://02800614023?

下图图片失败的提示,原因是天猫接口返回的商品数据如下:

{
item_id: 14292263734,
title: "XXXXXX",
img: "//img.alicdn.com/bao/uploaded/i2/821705368/TB1Us3Qcr_I8KJjy1XaXXbsxpXa_!!0-item_pic.jpg",
sold: "3",
quantity: 0,
totalSoldQuantity: 2937,
url: "//detail.m.tmall.com/item.htm?id=xxxxx",
price: "188.00",
titleUnderIconList: [ ]
},

不带协议名字!!!不知道是什么时候的历史留下的坑点吧!!!大厂也是有坑的!!

3、总结

具体的代码,可参考我github代码:

代码详细的解析还是参考这位大神的 利用Python爬虫爬取指定天猫店铺全店商品信息 - 晴空行 - 博客园,写的非常的详细!

整体来说,因为天猫的商品数据通过js来获取,所以比较容易获取到数据,而不用大量的爬取页面的商品,这个很赞!所以,爬虫这技术活,有很多方法,能找到好的方法,才是爬虫的最高境界啊!加油~

代码

python就是利害,一百行代码就搞定!


import os
import requests
import json
import csv
import random
import re
from datetime import datetime
from urllib import request
import time


class TM_producs(object):
    def __init__(self, storename):
        self.storename = storename
        self.url = 'https://{}.m.tmall.com'.format(storename)
        self.headers = {
            "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 "
                          "(KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"
        }
        datenum = datetime.now().strftime('%Y%m%d_%H%M%S')
        self.filename = '{}_{}.csv'.format(self.storename, datenum)
        self.get_file()

    def get_file(self):
        '''创建一个含有标题的表格'''
        title = ['item_id', 'product_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img']
        with open(self.filename, 'w', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=title)
            writer.writeheader()
        return

    def get_totalpage(self):
        '''提取总页码数'''
        num = random.randint(83739921, 87739530)
        endurl = '/shop/shop_auction_search.do?sort=s&p=1&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{}'
        url = self.url + endurl.format(num)
        html = requests.get(url, headers=self.headers).text
        infos = re.findall('\(({.*})\)', html)[0]
        infos = json.loads(infos)
        totalpage = infos.get('total_page')
        return int(totalpage)

    def get_products(self, page):
        '''提取单页商品列表'''
        num = random.randint(83739921, 87739530)
        endurl = '/shop/shop_auction_search.do?sort=s&p={}&page_size=12&from=h5&ajson=1&_tm_source=tmallsearch&callback=jsonp_{}'
        url = self.url + endurl.format(page, num)
        html = requests.get(url, headers=self.headers).text
        infos = re.findall('\(({.*})\)', html)[0]
        infos = json.loads(infos)
        products = infos.get('items')
        for product in products:
            del product['titleUnderIconList']
            item_id = product['item_id']
            product_id = self.get_product_spm(item_id)
            product['product_id'] = product_id
            imgUrl = 'https:' + product['img']
            self.save_img(imgUrl, product_id)
            item_id = product['item_id']

        # print(products)
        title = ['item_id', 'product_id', 'price', 'quantity', 'sold', 'title', 'totalSoldQuantity', 'url', 'img']
        with open(self.filename, 'a', encoding="utf-8", newline='') as f:
            writer = csv.DictWriter(f, fieldnames=title)
            writer.writerows(products)

    def get_product_spm(self, item_id):
        url = 'https://detail.m.tmall.com/item.htm?id={}'.format(item_id)
        html = requests.get(url, headers=self.headers).text
        # {"货号":"07300318000 "}
        product_id = re.findall(r'"货号":"(.+?)"}', html)[0].strip()
        print(product_id)
        return product_id

    def save_img(self, img_url, file_name):
        try:
            # 获得图片后缀
            file_suffix = os.path.splitext(img_url)[1]
            cwd = os.getcwd()
            save_path = os.path.join(cwd, 'images/')
            if not os.path.exists(save_path):
                os.makedirs(save_path)

            image_path = os.path.join(save_path, file_name + file_suffix)
            # 下载图片
            image = requests.get(img_url, headers=self.headers)
            # 命名并保存图片
            with open(image_path, 'wb') as f:
                f.write(image.content)

        except Exception as e:
            print('图片下载错误 :', file_name, e)

    def main(self):
        '''循环爬取所有页面宝贝'''
        total_page = self.get_totalpage()
        for i in range(1, total_page + 1):
            self.get_products(i)
            print('总计{}页商品,已经提取第{}页'.format(total_page, i))
            time.sleep(1 + random.random())


if __name__ == '__main__':
    storename = 'mgssp'
    tm = TM_producs(storename)
    tm.main()

参考


  • 如有疑问,欢迎在评论区一起讨论!
  • 如有不正确的地方,欢迎指导!


注:本文首发于 iHTCboy's blog,如若转载,请注来源

目录
相关文章
|
4天前
|
数据采集 存储 XML
构建高效的Python爬虫系统
【9月更文挑战第30天】在数据驱动的时代,掌握如何快速高效地获取网络信息变得至关重要。本文将引导读者了解如何构建一个高效的Python爬虫系统,从基础概念出发,逐步深入到高级技巧和最佳实践。我们将探索如何使用Python的强大库如BeautifulSoup和Scrapy,以及如何应对反爬措施和提升爬取效率的策略。无论你是初学者还是有经验的开发者,这篇文章都将为你提供宝贵的知识和技能,帮助你在信息收集的海洋中航行得更远、更深。
18 6
|
1天前
|
数据采集 存储 数据挖掘
深入探索 Python 爬虫:高级技术与实战应用
本文介绍了Python爬虫的高级技术,涵盖并发处理、反爬虫策略(如验证码识别与模拟登录)及数据存储与处理方法。通过asyncio库实现异步爬虫,提升效率;利用tesseract和requests库应对反爬措施;借助SQLAlchemy和pandas进行数据存储与分析。实战部分展示了如何爬取电商网站的商品信息及新闻网站的文章内容。提醒读者在实际应用中需遵守法律法规。
100 66
|
3天前
|
数据采集 数据挖掘 数据处理
Python中实现简单爬虫并处理数据
【9月更文挑战第31天】本文将引导读者理解如何通过Python创建一个简单的网络爬虫,并展示如何处理爬取的数据。我们将讨论爬虫的基本原理、使用requests和BeautifulSoup库进行网页抓取的方法,以及如何使用pandas对数据进行清洗和分析。文章旨在为初学者提供一个易于理解的实践指南,帮助他们快速掌握网络数据抓取的基本技能。
15 3
|
7天前
|
数据采集 JSON 数据格式
Python:南京地铁每日客流数据的爬虫实现
Python:南京地铁每日客流数据的爬虫实现
19 1
|
7天前
|
数据采集 Python
Python:某市公交线路站点的爬虫实现
Python:某市公交线路站点的爬虫实现
|
5天前
|
数据采集 存储 监控
如何使用 Python 爬取京东商品数据
如何使用 Python 爬取京东商品数据
17 0
|
5天前
|
数据采集 Linux 网络安全
python 爬虫遇到的aiohttp证书错误解决办法
python 爬虫遇到的aiohttp证书错误解决办法
20 0
|
2月前
|
机器学习/深度学习 数据采集 数据可视化
基于爬虫和机器学习的招聘数据分析与可视化系统,python django框架,前端bootstrap,机器学习有八种带有可视化大屏和后台
本文介绍了一个基于Python Django框架和Bootstrap前端技术,集成了机器学习算法和数据可视化的招聘数据分析与可视化系统,该系统通过爬虫技术获取职位信息,并使用多种机器学习模型进行薪资预测、职位匹配和趋势分析,提供了一个直观的可视化大屏和后台管理系统,以优化招聘策略并提升决策质量。
107 4
|
2月前
|
数据采集 存储 搜索推荐
打造个性化网页爬虫:从零开始的Python教程
【8月更文挑战第31天】在数字信息的海洋中,网页爬虫是一艘能够自动搜集网络数据的神奇船只。本文将引导你启航,用Python语言建造属于你自己的网页爬虫。我们将一起探索如何从无到有,一步步构建一个能够抓取、解析并存储网页数据的基础爬虫。文章不仅分享代码,更带你理解背后的逻辑,让你能在遇到问题时自行找到解决方案。无论你是编程新手还是有一定基础的开发者,这篇文章都会为你打开一扇通往数据世界的新窗。
|
3月前
|
数据采集 存储 JSON
从零到一构建网络爬虫帝国:HTTP协议+Python requests库深度解析
【7月更文挑战第31天】在网络数据的海洋中,使用Python的`requests`库构建网络爬虫就像探索未知的航船。HTTP协议指导爬虫与服务器交流,收集信息。HTTP请求包括请求行、头和体,响应则含状态行、头和体。`requests`简化了发送各种HTTP请求的过程。
72 4
下一篇
无影云桌面