• Python 爬取淘宝商品信息和相应价格


    !只用于学习用途!

    plt = re.findall(r'"view_price":"[d.]*"',html)

    :获得商品价格和view_price字段,并保存在plt中

    tlt = re.findall(r'"raw_title":".*?"',html)

    :获得商品名称和raw_price字段,并保存在tlt中 

    price = eval(plt[i].split(':')[1])

    :使用冒号分隔键值对,去掉前面的view_price字段,只获取其中价格部分

    tplt = "{:4} {:8} {:16}"

    :第一个位置给出大小为4,第二个位置大小为8,第三个位置大小为16

    import requests
    import re
     
    def getHTMLText(url):
        try:
            r = requests.get(url, 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 printGoodsList(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
        infoList = []
        for i in range(depth):
            try:
                url = start_url + '&s=' + str(44*i)
                html = getHTMLText(url)
                parsePage(infoList, html)
            except:
                continue
        printGoodsList(infoList)
         
    main()
    

      

  • 相关阅读:
    沈询:事务与分布式事务原理与实现
    c++ 幕客网
    Meet Dgraph — an open source, scalable, distributed, highly available and fast graph databas
    开发与系统管理----开发工具 左蓝
    奇虎360技术博客
    java 相关软件使用趋势
    长亭技术专栏 安全攻防技术分享
    tcp/ip RFC
    gentoo and arclinux
    孙鑫视频VC++深入详解学习笔记
  • 原文地址:https://www.cnblogs.com/yezhaodan/p/7486078.html
Copyright © 2020-2023  润新知