设为首页 加入收藏

TOP

淘宝商品定向爬取
2018-12-06 18:09:17 】 浏览:9
Tags:商品 定向

淘宝商品比价定向爬虫

功能描述:

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 = eva l(plt[i].split(':')[1])
              title = eva l(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()

 


编程开发网
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇py装饰器 下一篇爬虫之股票定向爬取

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

array(4) { ["type"]=> int(8) ["message"]=> string(24) "Undefined variable: jobs" ["file"]=> string(32) "/mnt/wp/cppentry/do/bencandy.php" ["line"]=> int(214) }