100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 爬虫(6)—— 淘宝商品比价定向爬虫

爬虫(6)—— 淘宝商品比价定向爬虫

时间:2021-01-15 16:13:10

相关推荐

爬虫(6)—— 淘宝商品比价定向爬虫

该实例来源于中国大学慕课,视频教学链接如下:

传送门

目标:

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

关键点:

淘宝的搜索接口

翻页的处理

从以上图片中可以看出,搜索接口的形式是:

/search?q=商品名

链接最后的数字代表的是下一页第一个商品的编号

技术:requests库,re库

整体代码框架

import requestsimport re# 获取页面信息def getHTMLText(url):print("url")# 页面解析def parsePage(ilt, html):print(ilt)# 显示商品信息def printGoodsList(ilt):print(goods)# 主函数def main():goods = '书包' # 商品depth = 2 # 获取页面的个数start_utl = '/search?q='+goodsinfoList = [] # 存取返回的商品信息for i in range(depth): # 处理每一页try:url = start_utl+'&s='+str(44*i)html = getHTMLText(url)parsePage = (infoList, html)except:continueprintGoodsList(infoList)main()

获取页面信息

def getHTMLText(url):try:r=requests.get(url,timeout=30)r.raise_for_status()r.encoding=r.apparent_encodingreturn r.textexcept:prnt("获取失败!")return ''

页面解析

从图片中可以看到价格信息位于:view_price关键字后;商品名位于raw_title关键字后面

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].spllit(':')[1])ilt.append([price,title])except:print("")

显示商品信息

def printGoodsList(ilt):tplt="{:4}\t{:8}\t{:16}" # 信息显示格式,4个单位,8个单位,16个单位print(tplt.format("序号","价格","商品名称"))count=0# 用于计数商品的个数for g in ilt:count+=1print(tplt.format(count,g[0],g[1]))

完整代码及运行结果

import requestsimport re# 获取页面信息def getHTMLText(url):try:r = requests.get(url, timeout=30)r.raise_for_status()r.encoding = r.apparent_encodingreturn r.textexcept:prnt("获取失败!")return ''# 页面解析def parsePage(ilt, html):print("html:----->",html)# html没问题,是网页的源码html='''"view_price":"88.00","view_fee":"0.00"raw_title":"tigerfamily小学生书包1-3年级男女孩儿童书包减负护脊背包6周岁"'''try:plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"', html) # 获取价格tlt = re.findall(r'\"raw_title\"\:\".*?\"', html)# 获取商品名称print("plt:")for i in range(len(plt)):price = plt[i].split(':')[1]title = tlt[i].split(':')[1]ilt.append([price,title])except TypeError as err:print(err)# 显示商品信息def printGoodsList(ilt):tplt = "{:4}\t{:8}\t{:16}" # 信息显示格式,4个单位,8个单位,16个单位print(tplt.format("序号", "价格", "商品名称"))count = 0# 用于计数商品的个数for g in ilt:count += 1print(tplt.format(count, g[0], g[1]))# 主函数def main():goods = '书包' # 商品depth = 1 # 获取页面的个数start_utl = '/search?q='+goodsinfoList = [] # 存取返回的商品信息for i in range(depth): # 处理每一页try:url = start_utl+'&s='+str(44*i)html = getHTMLText(url)parsePage(infoList, html)except:continueprintGoodsList(infoList)main()

视频中的是输出了正确的商品信息,但是自己做时输出的是空白数据,问题应该在页面解析处,获取网页源码没问题可以正常获得,但是解析不出数据。但是将html字符串修改一下,可以输出商品信息,不知道是代码问题还是我的软件问题

如果哪位大佬发现了问题,希望可以指出

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。