如下,爬取 http://tieba.baidu.com/p/4229162765 这个页面的图片并下载到桌面的 images 文件夹下:
#!/usr/bin/env python #-*- coding:utf-8 -*- ''' 以下代码在 PyCharm 中运行 ''' import re import urllib import urllib2
# 获取HTML源码 def getHTML(url): request = urllib2.urlopen(url) data = request.read() return data
# 对HTML源码进行过滤,过滤出图片的url,并下载图片 def getImages(html): regular = re.compile(r'<img class="BDE_Image" src="(.*?)".*?>') image_list = regular.findall(html) i = 1 for image in image_list: urllib.urlretrieve(image, filename='C:\\Users\\Administrator\\Desktop\\images\\%s.jpg' % i) i += 1 if __name__ == '__main__': url = 'http://tieba.baidu.com/p/4229162765' html = getHTML(url) getImages(html)