python简单爬虫
1、获取整个页面信息
getPageHtml.py
# coding=utf-8
import urllib
def getPageHtml(url):
page = urllib.urlopen(url)
html = page.read()
return html
html = getPageHtml("http://pic.baidu.com/")
print html
2、截取获取到的页面中需要的信息
通过html我们可以看出,我们需要抓取的图片信息为:
img src=”http://b.hiphotos.baidu.com/image/…..jpg”
在上述代码中加入:
import re
def getNeedImages(html):
pattern = r'src="(.+?\.(jpg|png|gif))"'
imgRe = re.compile(pattern)
images = re.findall(imgRe, html)
return images
print getNeedImages(html)
3、将截取到的信息保存到本地
def saveImages(images):
i = 0
for url in images:
urllib.urlretrieve(url[0], 'd:\img\%s.%s' % (i, url[1]))
i+=1
saveImages(getNeedImages(html))