首先进行相关的分析
要想爬取相关的信息,必须指导如下信息:
1、访问接口
2、翻页操作
首先进行搜索,得到相关的网址:https://s.taobao.com/search?q=书包&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170501
然后进行查看第二页的网址:https://s.taobao.com/search?q=书包&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170501&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=44
继续查看第三页的网址:https://s.taobao.com/search?q=书包&imgfile=&commend=all&ssid=s5-e&search_type=item&sourceId=tb.index&spm=a21bo.50862.201856-taobao-item.1&ie=utf8&initiative_id=tbindexz_20170501&bcoffset=4&ntoffset=4&p4ppushleft=1%2C48&s=88
进行仔细的观察就知道其中的奥妙所在
所以我们整个程序的设计结构如下:
1、提交商品搜索请求,循环获取页面
2、对于每个页面,提取商品名称和价格信息
3、将信息输出到屏幕上
主要的函数有
1、爬取网页
def getHTMLText(url): try: r=requests.get(url,timeout=30) r.raise_for_status() r.encoding=r.apparent_encoding return r.text except: print("")
2、进行信息提取
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("")
3、进行输出
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]))
4、主函数
def main(): goods='书包' depth=2 start_url='https://s.taobao.com/search?q='+goods infoList=[] for i in range(depth): try: #str函数的作用是将其中的内容转换为字符串 url=start_url+'&s='+str(44*i) html=getHTMLText(url) parsePage(infoList , html) except: continue printGoodsList(infoList)
import requests import re #获取页面函数、 def getHTMLText(url): try: r=requests.get(url,timeout=30) r.raise_for_status() r.encoding=r.apparent_encoding return r.text except: print("") #对获取页面进行解析 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: #str函数的作用是将其中的内容转换为字符串 url=start_url+'&s='+str(44*i) html=getHTMLText(url) parsePage(infoList , html) except: continue printGoodsList(infoList) main()