python爬虫由浅入深8---基于正则表达式查询的淘宝比价定向爬虫

技术路线:requests库和re库的整合

功能描述:

目标:获得淘宝搜索页面的信息,提取其中的商品名称和价格

理解:淘宝的搜索接口

   翻页的处理 程序如何处理网页翻页

首先,打开淘宝首页,搜索“书包”,,并翻页,发现导航栏的url为


由此即可确定我们所要爬取页面的url接口

然后,不得不看的就是网站的robots.txt协议咯,


呃呃呃,这个就很尴尬,但是,没有什么能够阻挡~~~我们对爬虫向往~~~~

具体咋办,再说吧。。。


程序的结构设计:

1.提交商品请求,循环获取页面

2.对于每个页面,提取商品名称和价格信息

3.将信息输出至屏幕

我们可以将每一步骤封装为一个函数,然后编写代码咯~~~~

通过查看网页源代码,可得与商品价格,以及商品名称相关的htmml代码




因为所要提取的信息并非是位于一个结构清晰的html结构标签内,故在此则不选用beautifulsoup,而是使用re正则表达式匹配搜索会更加方便一些


代码实现:

# -*-coding:utf-8-*-
import requests
import re
def getHTMMLText(url):
    try:
        r = requests.get(url,timeout = 30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return ""

def parserPage(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}\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 = getHTMMLText(url)
            parserPage(infoList,html)
        except:
            continue
    printGoodList(infoList)

main()












输出如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值