100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 淘宝商品比价定向爬虫实例介绍

淘宝商品比价定向爬虫实例介绍

时间:2019-05-15 08:10:44

相关推荐

淘宝商品比价定向爬虫实例介绍

功能描述

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

理解:淘宝的搜索接口&翻页的处理

技术路线:requests&re

“书包”:

变量s代表下一页起始商品的信息

定向爬虫的可能性:查看robots协议

程序的结构设计:

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

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

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

案例总结:

-采用了requests-re路线实现了淘宝商品比价定向爬虫

-熟练掌握正则表达式在信息提取方面的作用

代码:

import requestsimport redef getHTMLText(url):try:r=requests.get(url,timeout = 30)r.raise_for_statusr.encoding = r.apparent_encoding #是否使用,需要判断r.encoding是否能获取文件编码信息return r.textexcept: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]) #通过split方法分割:后面的部分只取价格title = eval(tlt[i].split(':')[1]) #eval去掉双引号ilt.append([price,title]) except:print("")def printGoodsList(ilt): #将淘宝得商品信息输出到屏幕上tplt = "{:4}\t{:8}\t{:16}" #规定输出格式print(tplt.format("序号","价格","商品名称"))count = 0for g in ilt :count = count +1 print(tplt.format(count,g[0],g[1]))def main():goods = 'packbage'depth = 2start_url = '/search?q='+goodsinfoList = []for i in range(depth):try:url = start_url + '&s=' +str(44*i) #每页起始有s=44*ihtml = getHTMLText(url)parsePage(infoList,html)except:continueprintGoodsList(infoList)#爬取得最终结果保存在infoList列表中main()

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