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,如若转载,请注来源

目录
相关文章
|
14天前
|
数据采集 存储 API
网络爬虫与数据采集:使用Python自动化获取网页数据
【4月更文挑战第12天】本文介绍了Python网络爬虫的基础知识,包括网络爬虫概念(请求网页、解析、存储数据和处理异常)和Python常用的爬虫库requests(发送HTTP请求)与BeautifulSoup(解析HTML)。通过基本流程示例展示了如何导入库、发送请求、解析网页、提取数据、存储数据及处理异常。还提到了Python爬虫的实际应用,如获取新闻数据和商品信息。
|
18天前
|
数据采集 Python
【python】爬虫-西安医学院-校长信箱
本文以西安医学院-校长信箱为基础来展示爬虫案例。来介绍python爬虫。
【python】爬虫-西安医学院-校长信箱
|
24天前
|
数据采集 安全 Python
python并发编程:Python实现生产者消费者爬虫
python并发编程:Python实现生产者消费者爬虫
25 0
python并发编程:Python实现生产者消费者爬虫
|
4天前
|
数据采集 存储 JSON
Python爬虫面试:requests、BeautifulSoup与Scrapy详解
【4月更文挑战第19天】本文聚焦于Python爬虫面试中的核心库——requests、BeautifulSoup和Scrapy。讲解了它们的常见问题、易错点及应对策略。对于requests,强调了异常处理、代理设置和请求重试;BeautifulSoup部分提到选择器使用、动态内容处理和解析效率优化;而Scrapy则关注项目架构、数据存储和分布式爬虫。通过实例代码,帮助读者深化理解并提升面试表现。
13 0
|
7天前
|
数据采集 JavaScript 前端开发
使用Python打造爬虫程序之破茧而出:Python爬虫遭遇反爬虫机制及应对策略
【4月更文挑战第19天】本文探讨了Python爬虫应对反爬虫机制的策略。常见的反爬虫机制包括User-Agent检测、IP限制、动态加载内容、验证码验证和Cookie跟踪。应对策略包括设置合理User-Agent、使用代理IP、处理动态加载内容、验证码识别及维护Cookie。此外,还提到高级策略如降低请求频率、模拟人类行为、分布式爬虫和学习网站规则。开发者需不断学习新策略,同时遵守规则和法律法规,确保爬虫的稳定性和合法性。
|
19天前
|
数据采集 存储 前端开发
Python爬虫如何快速入门
写了几篇网络爬虫的博文后,有网友留言问Python爬虫如何入门?今天就来了解一下什么是爬虫,如何快速的上手Python爬虫。
21 0
|
1月前
|
数据采集 存储 Web App开发
一键实现数据采集和存储:Python爬虫、Pandas和Excel的应用技巧
一键实现数据采集和存储:Python爬虫、Pandas和Excel的应用技巧
|
1月前
|
数据采集 前端开发 JavaScript
Python爬虫零基础到爬啥都行
Python爬虫项目实战全程实录,你想要什么数据能随意的爬,不管抓多少数据几分钟就能爬到你的硬盘,需要会基本的前端技术(HTML、CSS、JAVASCRIPT)和LINUX、MYSQL、REDIS基础。
20 1
Python爬虫零基础到爬啥都行
|
1月前
|
数据采集 Python
爬虫实战-Python爬取百度当天热搜内容
爬虫实战-Python爬取百度当天热搜内容
72 0
|
1月前
|
数据采集 存储 XML
深入浅出:基于Python的网络数据爬虫开发指南
【2月更文挑战第23天】 在数字时代,数据已成为新的石油。企业和个人都寻求通过各种手段获取互联网上的宝贵信息。本文将深入探讨网络爬虫的构建与优化,一种自动化工具,用于从网页上抓取并提取大量数据。我们将重点介绍Python语言中的相关库和技术,以及如何高效、合法地收集网络数据。文章不仅为初学者提供入门指导,也为有经验的开发者提供进阶技巧,确保读者能够在遵守网络伦理和法规的前提下,充分利用网络数据资源。