淘宝商品信息定向爬虫

淘宝商品信息定向爬虫

功能描述
  • 目标:获取淘宝搜索页面的信息,提取其中的商品名称和价格。
  • 理解:淘宝的搜索接口,翻页的处理
  • 技术路线:requests库,re库
分析网址
第一页 https://s.taobao.com/search?q=书包
第二页 https://s.taobao.com/search?q=书包&s=44
程序的结构设计

​ 步骤1:提交商品的搜索请求,循环获取页面。

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

​ 步骤3:将信息输出到屏幕上。

代码编写
import requests
import re


def getHTMLText(url):
    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'}
        r = requests.get(url, headers=headers)
        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}\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 = 2
    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()

        
发布了31 篇原创文章 · 获赞 90 · 访问量 9953

猜你喜欢

转载自blog.csdn.net/Jarrodche/article/details/98884601