1、Python网络爬虫获取淘宝商品价格代码:
#-*-coding:utf-8-*-
'''
Created on 2017年3月17日
@author: lavi
'''
import requests
from bs4 import BeautifulSoup
import bs4
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:
return ""
def parserPage(goodsList,html):
tlt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
plt = re.findall(r'\"raw_title\"\:\".*?\"',html) #添加问号使用最小匹配的
for i in range(len(tlt)):
title = eval(tlt[i].split(':')[1]) #eval()函数十分强大,可以将将字符串str当成有效的表达式来求值并返回计算结果
price = eval(plt[i].split(':')[1])
goodsList.append([title,price])
def printPage(goodsList):
tplt="{:6}\t{:8}\t{:16}"
print(tplt.format("序号","价格","商品名称"))
for i in range(len(goodsList)):
goods = goodsList[i]
print(tplt.format(i+1,goods[0],goods[1]))
def main():
goods = "书包"
depth = 2;
url = "https://s.taobao.com/search?q="
goodsList = []
for i in range(depth):
html = getHTMLText(url+goods+"&s="+str(i*44))
parserPage(goodsList, html)
printPage(goodsList)
main()
2、eval()函数使用扩展
eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。so,结合math当成一个计算器很好用。另外可以把list,tuple,dict和string相互转化。
a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
b = eval(a)
b
Out[3]: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
type(b)
Out[4]: list
a = "{1: 'a', 2: 'b'}"
b = eval(a)
b
Out[7]: {1: 'a', 2: 'b'}
type(b)
Out[8]: dict
a = "([1,2], [3,4], [5,6], [7,8], (9,0))"
b = eval(a)
b
Out[11]: ([1, 2], [3, 4], [5, 6], [7, 8], (9, 0))
可于看到eval()函数的功能十分强大,但是安全性也是其致命的缺点。想一想这种使用环境:需要用户输入一个表达式,并求值。如果用户恶意输入:
__import__('os').system('dir')
那么eval()之后,你会发现,当前目录文件都会展现在用户前面。那么继续输入:
open('文件名').read()
代码都给人看了。获取完毕,一条删除命令,文件消失。
3、Python正则表达式的最小匹配
Python中正则表达式re模块默认使用贪婪匹配,即最大匹配。但我们也有需要使用最小匹配的时候,下面就来看看什么是最下匹配,以及如何实现最小匹配:
最短匹配应用于:假如有一段文本,你只想匹配最短的可能,而不是最长。
例子
比如有一段html片段,'\this is first label\\the second label\',如何匹配出每个a标签中的内容,下面来看下最短与最长的区别。
代码
import re
>>> str = 'this is first labelthe second label'
>>> print re.findall(r'(.*?)', str) # 最短匹配
['this is first label', 'the second label']
>>> print re.findall(r'(.*)', str)
['this is first labelthe second label']
解释
参考资料:
1、中国大学MOOCPython网络爬虫与信息提取课程
2、http://www.tuicool.com/articles/BBVnQbq
3、http://www.cnblogs.com/jhao/p/5989241.html