小爬虫

一个从百度贴吧,爬取图片的例子。

urllib,urllib2,re

函数

page=urllib.urlopen("http://...")  返回一个网页对象

html=page.read()   读取网页的html源码

urllib.urlretrieve()  下载资源到本地

代码

#coding:utf8
import re
import urllib

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

def getImgUrl(html):
    reg=r"src="(.*?.jpg)""#?非贪婪匹配,()分组只返回分组结果,外单引号内双引号
    imgre=re.compile(reg)#编译正则表达式,加快速度
    imglist=re.findall(imgre,html)
    return imglist
url="http://tieba.baidu.com/p/3162606526"#贴吧地址
html=getHtml(url)
ImgList=getImgUrl(html)
ImgList= ImgList[1:10]#取前10个下载
print ImgList
x=0
for imgurl in ImgList:
    urllib.urlretrieve(imgurl,"%s.jpg" %x)
    x+=1
文章导航