Python抓取淘宝美人库

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011371360/article/details/78541062

废话不多说,首先上图:
抓取结果.png
抓取图片.png
这是抓取了一个多小时的结果,代码没有做过优化,也没用多线程、分布式,就用最简单的结构爬取,速度大概在3500条/小时。第一张图片展示的是数据库中抓取的信息(姓名、城市、身高、体重、个人主页url、图片url),第二张展示的是保存下来的信息(.txt + .jpg)。

下面讲一下爬取过程。按步骤来

1、目标网页分析。淘宝美人库

网站页面图
淘女郎-美人库.png
用chrome的页面检查工具(F12)查看页面加载过程
这里写图片描述

发现首页链接的Response中并没有返回页面内容,因为网站采用的是动态加载,那我们就开始找内容请求的Request
这里写图片描述

在众多Request中我们找到了如上图红圈中的Request,这就是我们要找的页面内容请求Request,返回的Response是json,看一下请求信息
这里写图片描述
这里写图片描述
这是一个POST请求,观察post参数不难发现关键参数’currentPage’,猜测修改该参数就可获取不同页面的内容,将url验证一下
这里写图片描述
没毛病!
这样一来,目标网页分析完毕!
通过对url(https://mm.taobao.com/tstar/search/tstar_model.do?_input_charset=utf-8) post相应参数就可获取页面内容,控制参数’current Page‘就可以遍历页面内容。

2、代码实现。

(1)下载器实现

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
param = {'_input_charset': 'utf-8',
          'q': '',
          'viewFlag': 'A',
          'sortType': 'default',
          'searchStyle': '',
          'searchRegion': 'city',
          'searchFansNum': '',
          'currentPage': '',
          'pageSize': '20'
          }
url = 'https://mm.taobao.com/tstar/search/tstar_model.do'

def getJson(page):
    param['currentPage'] = str(page)
    params = parse.urlencode(param).encode('utf-8')
    req = request.Request(url, data=params, headers=headers)
    content = request.urlopen(req)
    content = json.loads(content.read().decode('gbk'))
    # 如果出错会返回 'status' = -1
    if content['status'] == -1:
        return -1
    #print(content)
    return content

(2)解析器实现

def parserJson(content, page):
    mmList = []

    data = content['data']['searchDOList']
    for l in data:
        temp = {}
        temp['id'] = str(l['userId'])
        temp['name'] = l['realName']
        temp['city'] = l['city']
        temp['height'] = str(l['height'])
        temp['weight'] = str(l['weight'])
        temp['favornum'] = str(l['totalFavorNum'])
        temp['profile'] = 'http:'+l['avatarUrl']
        temp['pic'] = 'http:'+l['cardUrl']
        #print(temp)
        mmList.append(temp)
        mkdir(temp['name'])
        print('第%s页-->正在抓取%s'%(page, temp['name']))
        getImg(temp['profile'], temp['name'], 'profile')
        getImg(temp['pic'], temp['name'], 'pic')
        if not os.path.exists('./'+temp['name']+'/info.txt'):
            with open('./'+temp['name']+'/info.txt', 'w') as f:
                f.write(temp['name']+'\n')
                f.write(temp['city']+'\n')
                f.write(temp['height']+'\n')
                f.write(temp['weight']+'\n')

    return mmList

(3)图片保存

def mkdir(path):
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        print('目录已存在!')

def getImg(url, path, name):
    if os.path.exists('./' + path + '/' + name + '.jpg'):
        print('文件已存在!')
        return 0
    try:
        req = request.Request(url, headers=headers)
        reponse = request.urlopen(req)
        get_img = reponse.read()
        with open('./' + path + '/' + name + '.jpg', 'wb') as fp:
            fp.write(get_img)
    except error.URLError as e:
        print(e.reason)

(4)主程序

#python3.6

from urllib import request, parse, error
import json
import os

if __name__ == '__main__':
    page = 1
    while True:
        content = getJson(page)
        if content == -1:
            print('抓取完毕!')
            exit()
        parserJson(content, page)
        page += 1

以上就把各位MM的高清照片(1张或2张)以及简介信息下载到本地了,如果嫌占内存,可以把数据保存在数据库中,随时可以拿来用(比如后续想通过个人主页url访问个人信息)。以下添加数据库保存代码。

数据库保存

#使用mysql数据库

import pymysql

tablename = 'taobaomm'  # 定义一张表名
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='root', db='mysql', charset='utf8')
cur = conn.cursor()
cur.execute('USE ***')  # 选择一个数据库
try:
    cur.execute('CREATE TABLE '+tablename+' (id BIGINT(7) NOT NULL AUTO_INCREMENT, name VARCHAR(100), city VARCHAR(20), height VARCHAR(10), weight VARCHAR(10), homepage VARCHAR(100), profile VARCHAR(100), pic VARCHAR(100), created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(id))')
except:
    pass
#以下使数据库支持中文不乱码
cur.execute('ALTER DATABASE wyq CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE name name VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE city city VARCHAR(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE height height VARCHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE weight weight VARCHAR(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE homepage homepage VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE profile profile VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')
cur.execute('ALTER TABLE '+tablename+' CHANGE pic pic VARCHAR(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci')

def store(name, city, height, weight, hompage, profile, pic):
    cur.execute('INSERT INTO '+tablename+' (name, city, height, weight, homepage, profile, pic) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")', (name, city, height, weight, hompage, profile, pic))
    cur.connection.commit()

只需在解析器里调用数据存储函数store()即可。
嗯,就是这么简单

*完整代码在这里:淘宝美人库

猜你喜欢

转载自blog.csdn.net/u011371360/article/details/78541062