python小爬虫【1】

爬取百度贴吧的图片

分析贴吧源代码,图片所在位置是:<img class="BDE_Image" src=“。。。。。。。.jpg” pic_ext。。。。。

所以正则匹配是:

r'BDE_Image" src="(.+?\.jpg)" pic_ext'

(注:?表示懒惰匹配,如果不加?会造成匹配到一个"BDE_Image" src=“起始到网页最后一个pic_ext结束的一个串。

           ()表示所要提取的字符串,即。。。。.jpg

代码如下:

#!usr/bin/env python
# coding: utf-8

import os
import re
import urllib

def getHtml(url):
    page = urllib.urlopen(url)
    html = page.read()
    page.close()
    return html

def getImages(html):
    reg = r'BDE_Image" src="(.+?\.jpg)" pic_ext'
    imgre =  re.compile(reg)
    imgList = imgre.findall(html)
    print 'We have got %d pictures' % len(imgList)
    path = './download'
    x = 0
    for imgurl in imgList:
        FileName = os.path.join(path, '%s.jpg' % (x+1))
        urllib.urlretrieve(imgurl,FileName)
        print '%s.jpg is done.' % (x+1)
        x = x + 1

if __name__ == '__main__':
    url = raw_input('input the URL:>')
    html = getHtml(url)
    getImages(html)

还是最为基础的功能。

posted @ 2013-12-07 15:21  木叶火影  阅读(481)  评论(0编辑  收藏  举报