学习网络爬虫的第一个程序:
#-*- coding:utf-8 -*- #使用utf-8字符集
import re
import urllib
def get_content(url):
""" 获取页面源码"""
html = urllib.urlopen(url) #获取网站页面的地址
content = html.read() #将页面读取到content变量中
html.close() #关闭页面
return content
def get_images(info):
""" 获取页面里面的图片 """
regex = r'class="BDE_Image" pic_type="." width="..." height="..." src="(.+?\.jpg)"' #正则表达式匹配查找出图片的地址 . 表示这里可以是任意一个字符 .+?\.jpg 表示这里可以是任意字符串直到出现.jpg为止
pat = re.compile(regex)
image_code = re.findall(pat,info)
#print image_code #打印出匹配的对象
print len(image_code) #打印出总共匹配了多少张图片
i = 1
for image_url in image_code:
print image_url
urllib.urlretrieve(image_url,'%s.jpg' % i) #下载图片并命名为 i.jpg
i +=1
info = get_content('http://tieba.baidu.com/p/3833299105')#页面地址
print get_images(info)
`