淘宝商品定向爬取

2018-12-09 11:20:41来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

淘宝商品比价定向爬虫

功能描述:

1、目标:获取淘宝搜索页面的信息,提取其中的商品名称和价格

2、理解:淘宝的搜索接口,翻页处理

 

技术路线:requests + re

程序的结构设计:

1、提交商品搜索的请求,循环获取页面。

2、对于每个页面,提取商品名称和价格信息。

3、将信息输出到屏幕上。

 

重要:在淘宝获取页面时,淘宝设置了登录验证才能访问,此时在requests请求时,需要设置cookies和user-agent。

import requests
import re

def getHTMLText(url,kv,cookies):
    try:
        r=requests.get(url,headers = kv,cookies = cookies,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)
        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 g in ilt:
        count = count +1 
        print(tplt.format(count,g[0],g[1]))


def main():
    goods = '书包'
    depth = 3
    start_url = 'https://s.taobao.com/search?&q=' + goods
    coo = 'thw=cn; t=254ecf83ad9b49c70d383c71e214fab2;cna=kbBgFFO2dU8CAXFzKR/6/wq5; tg=0;enc=xWaBwIc%2BqZfhPca6P6g4cz34emAsVK3LjzRsT%2FkMfk5Ja31%2BmjMxGvBDJ%2B82Q2pJLJ83dUH5lBPAw%2BpI53L4%2BQ%3D%3D; hng=CN%7Czh-CN%7CCNY%7C156; x=e%3D1%26p%3D*%26s%3D0%26c%3D0%26f%3D0%26g%3D0%26t%3D0; tracknick=xxp158125132; lgc=xxp158125132; _cc_=URm48syIZQ%3D%3D; uc3=vt3=F8dByR1TOm%2BGeyLp6rE%3D&id2=VWeYZoAnISaO&nk2=G5htj%2BHk8f8ST03J&lg2=W5iHLLyFOGW7aA%3D%3D; mt=ci=94_1; v=0; cookie2=1794e2e0aad3f137168e0a64b250dced; _tb_token_=e33e0373befbe; isg=BEtLnz2UkxogtcghrE2mANjZ2u8_4F80dJ1mYL1IJwrh3Gs-RbDvsul6spyXJ7da'
   cookies = {}
    for line in coo.split(';'):
        name,value=line.strip().split('=',1)
        cookies[name]=value
    kv = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36'}
    infoList = []
    for i in range(depth):
        try:
            url = start_url+'&s=' + str(44*i)
            html = getHTMLText(url,kv,cookies)
            parsePage(infoList,html)
        except:
            continue
    printGoodsList(infoList)


main()

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Pycharm中,pyqt5.11.1的Qt assistant显示

下一篇:Python入门---time模块