Python爬取淘宝商品附加cookie修改

PYTHON爬取淘宝商品附加cookies

  • 简单的Python爬取淘宝商品路线
    • 第一步确定url
    • 第二步获得html文档
    • 第三步简析信息
    • 第四步打印信息

简单的Python爬取淘宝商品路线

利用Pyhton可爬取淘宝商品,爬取技术路线为:requests-bs4-re,当所需信息可通过源代码中很轻松查找到时,直接利用正则表达式即可,本文即为直接利用正则表达式获取相关信息。
目标:获得目标商品前3页的价格、名称,本文以书包为例,参考了慕课python课程。下图为爬取结果部分图。
Python爬取淘宝商品附加cookie修改_第1张图片
以下为具体步骤。

第一步确定url

通过requests.get方法可以轻松通过链接获得商品信息,但在此之前需要确定url。打开淘宝搜索‘书包’,发现url分别为:
第一页:https://s.taobao.com/search?q=书包&imgfile…48&s=0
第二页:https://s.taobao.com/search?q=书包&imgfile…48&s=44
第三页:https://s.taobao.com/search?q=书包&imgfile…48&s=88
可以从url中推测可知,’书包‘为搜索词,可以用goods来表示所提交的搜索关键词;0、44、88分别为当前页第一个商品的编号,如此可以用i*44来实现爬取第i页。

第二步获得html文档

常规爬取直接采用requests库中get方法即可,但目前淘宝需要登陆才可爬取相关内容,所以需要增加headers、cookies内容。这里可以通过chrome浏览器在登陆淘宝之后通过开发者模式中的网络中查询登陆淘宝时的cookies和user-gent,将此作为爬虫软件的模拟浏览器提交请求时的信息。

// get cookies and headers
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}
usercookies='thw=cn; ........'

值得注意的是,cookies要求是字典格式,所以采用split分割字符串,并利用字典赋值实现格式转换。

//的
cookies={}
for a in usercookies.split(';'):
        name,value=a.strip().split('=',1)
        cookies[name]=value

在完成以上步骤后,即可用requests库获得html文档了。

第三步简析信息

通过查看淘宝商品源代码,发现所有商品的价格、名称在html文档中即可查询到,所以利用正则表达式获得相关名称和价格,并通过列表将上述信息存储。详情见完整代码。

第四步打印信息

先设置好打印格式,再通过列表遍历打印出相对应的商品价格和名称。详情见完整代码。
以上附上完整代码。

//get_goods_from_taobao
import requests
import re

def getHTMLText(url):
    headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'}
    usercookies='thw=cn;.......'
    cookies={}
    for a in usercookies.split(';'):
        name,value=a.strip().split('=',1)
        cookies[name]=value
    try:
        r=requests.get(url,cookies=cookies,headers=headers,timeout=60)
        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)
        for i in range(len(plt)):
            price=eval(plt[i].split(':')[1])
            title=eval(tlt[i].split(':')[1])
            ilt.append([price,title])
    except:
        print('')
def printGoodList(ilt):
    tplt='{:4}\t{:8}\t{:16}'
    print(tplt.format('序号','价格','名称'))
    count=0
    for c in ilt:
        count=count+1
        print(tplt.format(count,c[0],c[1]))
def main():
    goods='书包'
    depth=4
    start_url='http://s.taobao.com/search?q='+goods
    infoList=[]
    for i in range(depth):
        try:
            url=start_url+'&s='+str(44*i)
            html=getHTMLText(url)
            parsePage(infoList,html)
        except:
            continue
    printGoodList(infoList)
main()

当然除了价格以外,还可以获取销量、好评数等信息,为自己购物提供指导建议。

最后,分享一句话:
坚持,多坚持一天多收获一天!

你可能感兴趣的:(Python)