python:淘宝商品信息定向爬取

'''
程序的结构设计
步骤1:提交商品的搜索请求,循环获取页面
步骤2:对于每个页面,提取商品名称和价格信息
步骤3:将信息输出到屏幕上
'''
import requests
import re


def getHTMLText(url):
    try:
        r = requests.get(url, timeout=30)
        r.raise_for_status()  # 如果状态不是200,抛出HTTPError异常
        r.encoding = r.apparent_encoding
        return r.text
    except:
        print("-----")


def parsePage(ulist, html):
    try:
        plt = re.findall(r'\"view_price\"\:\".*?\"', html)  # 返回一个列表,价格
        tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)  # 商品名称
        llt = re.findall(r'\"item_loc\"\:\".*?\"', html)  # 产地
        for i in range(len(plt)):
            price = eval(plt[i].split(":")[1])  # '"view_price":"99.00"', 去点最外层的引号,再分割,再取得后面想要的信息
            title = eval(tlt[i].split(":")[1])
            location = eval(llt[i].split(":")[1])
            ulist.append([price, location, title])#添加入列表
    except:
        print("-----")


def printGoodsList(ulist):
    tplt = "{:4}\t{:8}\t{:10}\t{:16}"#定义打印出的格式
    print(tplt.format("序号", '价格', "产地", "商品名称"))
    count = 0#表明商品的序号
    for g in ulist:
        count = count + 1
        print(tplt.format(count, g[0], g[1], g[2]))


def main():
    goods = "耳机"  # 要搜索的商品
    depth = 2  # 爬取2页信息
    starturl = 'https://s.taobao.com/search?q=' + goods
    infolist = []
    for i in range(depth):
        try:
            url = starturl + '&s=' + str(44 * i)
            html = getHTMLText(url)
            parsePage(infolist, html)
        except:
            continue
    printGoodsList(infolist)


main()

可以根据不同的需求来添加你要爬取的信息
想爬取更多的耳机,那么就改变depth
想爬取更多关于耳机的内容,那么就查看源代码,使用正则表达式来完成。

猜你喜欢

转载自blog.csdn.net/Yk_0311/article/details/81632321