zoukankan      html  css  js  c++  java
  • 淘宝商品定向爬取

    淘宝商品比价定向爬虫

    功能描述:

    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}	{:8}	{: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()
  • 相关阅读:
    QuartzNet使用
    Flex Metadata tags 元数据标签
    fb设置viewSourceURL
    免费开放的API
    测试跨域加载
    nape.geom.MarchingSquares
    bootstrap 全局样式
    <meta> 标记汇总
    bootstrap模版兼容IE浏览器代码嵌入
    正则表达式语法
  • 原文地址:https://www.cnblogs.com/jiarenanhao/p/10078023.html
Copyright © 2011-2022 走看看