技术路线: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()
输出如下: