Python3简单的爬取淘宝商品数据

前言

JS学习刚刚开始中,因为一些奇怪的原因,对爬虫感兴趣,然后就想着能不能写一个爬淘宝商品的python。
python语法0基础,在看别人的代码中借鉴学习,对请求什么的都一知半解。
愣头青丝毫不怵,反正就凑出来这个代码。

后来写的爬取1688的程序
好像还更简单一点:另一个Python3爬取实例(1688)

使用的软件

  • vscode
  • Chrome

环境

  • Python3

实现代码

v1 手动传入cookies版本

用到的库
  • re 正则表达式 内置的
  • requests 我安装的第一个库,用来处理http请求的(大概)
  • xlwt 这是个处理excel文件的库

一开始写的是通过手动传入cookies
解决淘宝要登陆才能搜索的限制

import requests
import re
import xlwt

def writeExcel(ilt,name):
    if(name != ''):
        count = 0
        workbook = xlwt.Workbook(encoding= 'utf-8')
        worksheet = workbook.add_sheet('temp')
        worksheet.write(count,0,'序号')
        worksheet.write(count,1,'购买')
        worksheet.write(count,2,'价格')
        worksheet.write(count,3,'描述')
        for g in ilt:
            count = count + 1
            worksheet.write(count,0,count)
            worksheet.write(count,1,g[0])
            worksheet.write(count,2,g[1])
            worksheet.write(count,3,g[2])
        workbook.save(name+'.xls')
        print('已保存为'+name+'.xls')
    else:
        printGoodsList(ilt)

def getHTMLText(url,cookies):
    kv = {'cookie':cookies,'user-agent':'Mozilla/5.0'}
    try:
        r = requests.get(url,headers=kv, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""
     
def parsePage(ilt, html):
    try:
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
        sls = re.findall(r'\"view_sales\"\:\".*?\"',html)
        for i in range(len(plt)):
            sales = eval(sls[i].split(':')[1])
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            ilt.append([sales , price , title])
    except:
        print("")
 
def printGoodsList(ilt):
    tplt = "{:4}\t{:8}\t{:16}\t{:32}"
    print(tplt.format("序号", "购买","价格", "商品名称"))
    count = 0
    for g in ilt:
        count = count + 1
        print(tplt.format(count, g[0], g[1],g[2]))

def main():
    cookies = input('传入cookies:')
    goods = input('搜索商品:')
    depth = int(input('搜索页数:'))
    name = input('输入保存的excel名称(留空print):')
    start_url = 'https://s.taobao.com/search?q=' + goods
    infoList = []
    print('处理中...')
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(44*i)
            html = getHTMLText(url,cookies)
            parsePage(infoList, html)
            print('第%i页成功' %(i+1))
        except:
            continue
    writeExcel(infoList,name)
    print('完成!')
     
main()

找了一些网上的类似py程序,觉得他们的描述有点...奇怪?
(可能他们扒的是评论吧,评论好像是js传入)

搜索页面好像结构很简单,url都直接传入中文。
当时也没什么好办法解决cookies的问题,模拟登陆感觉又很麻烦。
就留了个input给cookies手动传入。

函数部分

拿网页

def getHTMLText(url,cookies):
    kv = {'cookie':cookies,'user-agent':'Mozilla/5.0'}
    try:
        r = requests.get(url,headers=kv, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

头文件是kv,里面就一个cookies和user-agent,给request加了个timeout参数。
用的函数 requests.get()
我目前知道的参数还有params,这个是加在url后面的。
url是目标网址,传入的是'https://s.taobao.com/search?q=商品名字'
headers是http请求的头文件。
这里我又接触了一点点点点的JSON,还未学习。
r.raise_for_status()应该是用来抛出异常的。
成功的请求r.status_code的值是200。
requests的对象有个text,就是拿到的文本文件。

处理内容

def parsePage(ilt, html):
    try:
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
        sls = re.findall(r'\"view_sales\"\:\".*?\"',html)
        for i in range(len(plt)):
            sales = eval(sls[i].split(':')[1])
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            ilt.append([sales , price , title])
    except:
        print("")

对page的处理,用正则re.findall匹配html里含有view_prive等内容的部分,取出来的是个数组,然后写个循环把每项都放到之前声明好的ilt数组里。
python的for循环好像都是in?然后用range()里放数字进行数字循环,用len()里放数组读数组长度。还是挺好理解的,纪念一下理解的第一个python循环。

写结果到excel/直接打印结果

def writeExcel(ilt,name):
    if(name != ''):
        count = 0
        workbook = xlwt.Workbook(encoding= 'utf-8')
        worksheet = workbook.add_sheet('temp')
        worksheet.write(count,0,'序号')
        worksheet.write(count,1,'购买')
        worksheet.write(count,2,'价格')
        worksheet.write(count,3,'描述')
        for g in ilt:
            count = count + 1
            worksheet.write(count,0,count)
            worksheet.write(count,1,g[0])
            worksheet.write(count,2,g[1])
            worksheet.write(count,3,g[2])
        workbook.save(name+'.xls')
        print('已保存为'+name+'.xls')
    else:
        printGoodsList(ilt)

def printGoodsList(ilt):
    tplt = "{:4}\t{:8}\t{:16}\t{:32}"
    print(tplt.format("序号", "购买","价格", "商品名称"))
    count = 0
    for g in ilt:
        count = count + 1
        print(tplt.format(count, g[0], g[1],g[2]))

在输入时input设置了一项是excel的名称,如果留空的话就转到print直接打印在屏幕上。这个xlwt库我也是边看边写。
就会用三个函数 :

  • workbook = xlwt.Workbook(encoding = 'UTF-8')
  • wirksheet = workbook.add_sheet('temp)
  • worksheet.write()
  • workbook.save()

打开?/创建excel,创建sheet,写入数据,保存表。
write有三个参数(行,列,内容)
打印用的tplt.format()也差不多吧

主函数

def main():
    cookies = input('传入cookies:')
    goods = input('搜索商品:')
    depth = int(input('搜索页数:'))
    name = input('输入保存的excel名称(留空print):')
    start_url = 'https://s.taobao.com/search?q=' + goods
    infoList = []
    print('处理中...')
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(44*i)
            html = getHTMLText(url,cookies)
            parsePage(infoList, html)
            print('第%i页成功' %(i+1))
        except:
            continue
    writeExcel(infoList,name)
    print('完成!')
     
main()

Python 的语法结构好像是先执行没有函数声明def的?
然后之前好像还有看到if _ main _ = _ main _ 还是什么的作为程序入口的,不是很懂。反正丢一个main()在那可以运行就行了。

主函数就这样喽,淘宝页面的页数是44*n的,第一页是0,第二页44,第三页88这样,所以这样写的

v2 Chrome传入cookies版本

这个版本多了一个部分,从网上摘了一些代码加进去。

import os
import re
import xlwt
import sqlite3
import requests
from win32.win32crypt import CryptUnprotectData

def getcookiefromchrome():
    host = '.taobao.com'
    cookies_str = ''
    cookiepath=os.environ['LOCALAPPDATA']+r"\Google\Chrome\User Data\Default\Cookies"
    sql="select host_key,name,encrypted_value from cookies where host_key='%s'" % host
    with sqlite3.connect(cookiepath) as conn:
        cu=conn.cursor()        
        cookies={name:CryptUnprotectData(encrypted_value)[1].decode() for host_key,name,encrypted_value in cu.execute(sql).fetchall()}
        for key,values in cookies.items():
                cookies_str = cookies_str + str(key)+"="+str(values)+';'
        return cookies_str

def writeExcel(ilt,name):
    if(name != ''):
        count = 0
        workbook = xlwt.Workbook(encoding= 'utf-8')
        worksheet = workbook.add_sheet('temp')
        worksheet.write(count,0,'序号')
        worksheet.write(count,1,'购买')
        worksheet.write(count,2,'价格')
        worksheet.write(count,3,'描述')
        for g in ilt:
            count = count + 1
            worksheet.write(count,0,count)
            worksheet.write(count,1,g[0])
            worksheet.write(count,2,g[1])
            worksheet.write(count,3,g[2])
        workbook.save(name+'.xls')
        print('已保存为:'+name+'.xls')
    else:
        printGoodsList(ilt)

def getHTMLText(url):
    cookies = getcookiefromchrome()
    kv = {'cookie':cookies,'user-agent':'Mozilla/5.0'}
    try:
        r = requests.get(url,headers=kv, timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""
     
def parsePage(ilt, html):
    try:
        plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
        tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
        sls = re.findall(r'\"view_sales\"\:\".*?\"',html)
        for i in range(len(plt)):
            sales = eval(sls[i].split(':')[1])
            price = eval(plt[i].split(':')[1])
            title = eval(tlt[i].split(':')[1])
            ilt.append([sales , price , title])
    except:
        print("")
 
def printGoodsList(ilt):
    tplt = "{:4}\t{:8}\t{:16}\t{:32}"
    print(tplt.format("序号", "购买","价格", "商品名称"))
    count = 0
    for g in ilt:
        count = count + 1
        print(tplt.format(count, g[0], g[1],g[2]))

def main():
    goods = input('搜索商品:')
    depth = int(input('搜索页数:'))
    name = input('输入保存的excel名称(留空print):')
    start_url = 'https://s.taobao.com/search?q=' + goods
    infoList = []
    print('处理中...')
    for i in range(depth):
        try:
            url = start_url + '&s=' + str(44*i)
            html = getHTMLText(url)
            parsePage(infoList, html)
            print('第%i页成功...' %(i+1))
        except:
            continue
    writeExcel(infoList,name)
    print('完成!')

main()

这个就多了一个函数,单独看多出来的函数:

从Chrome拿cookies数据

import os
import sqlite3
from win32.win32crypt import CryptUnprotectData

def getcookiefromchrome():
    host = '.taobao.com'
    cookies_str = ''
    cookiepath=os.environ['LOCALAPPDATA']+r"\Google\Chrome\User Data\Default\Cookies"
    sql="select host_key,name,encrypted_value from cookies where host_key='%s'" % host
    with sqlite3.connect(cookiepath) as conn:
        cu=conn.cursor()        
        cookies={name:CryptUnprotectData(encrypted_value)[1].decode() for host_key,name,encrypted_value in cu.execute(sql).fetchall()}
        for key,values in cookies.items():
                cookies_str = cookies_str + str(key)+"="+str(values)+';'
        return cookies_str

为他导了三个库!
我总觉得还有很大的可以优化的空间。
而且这个是针对Chrome的cookies缓存位置,没在Chrome登过淘宝就没用了。
pywin32我装了好久才成功,他在vscode里还会一直报错,虽然运行不影响。

大意应该是打开那个路径,然后解码cookies,然后把他拿出来。

从网上摘的函数是直接return cookies
然后放到头文件里发请求,发现拿不到数据!
对比一下发现cookies是一个dict,格式跟他要求的好像不一样?
我也不会什么字典相关操作,就只能简单的,把key和value用循环拼凑成一个满足cookies条件的str,我总觉得应该是有相关函数的,能省一些循环的资源,不过这样也行。
然后再把主函数的cookies部分改一改就成了。

讨论

扒12页没有问题,再多的没有试过。
好像据说淘宝有反爬虫?如果爬太多可能拿不到数据?
(爬太多也不该用excel吧!)
但是好像爬这个的过程,跟人用浏览器访问没什么区别
识别方法可能是同一个IP快速访问多页,这只有爬虫能做到
那加个延时应该能应对,虽然我不知道延时函数怎么写,搜就完事了。

还有看到说淘宝的网页是ajax动态加载的,可是....好像不是欸?(可能是评论吧)

感觉扒评论比较有价值,可以调查一下大家买的都是什么型号这样子。
可是想写才发觉,我好像不会python。

我还是老老实实的回去把JS 30天挑战先完成掉吧,然后认真的自己写一个网页,搞明白CSS的各种问题(现在好多搞不灵清),然后去看看Jquery看看PHP,如果有信心完成一个不错的个人网站,那么就去租VPS喽。

  • 用hexo搭建博客真简单,跳过了所有css布局和页面设计,hexo g,网页就生成了

你可能感兴趣的:(Python3简单的爬取淘宝商品数据)