*----------------------------------------------------------------编程届菜鸟-------------------------------------------------------*
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib.request
import re
def getHtml(url):
page = urllib.request.urlopen(url)
html=page.read()
return html
def getImg(html):
reg = r'src="(.+?\.jpg)" pic_ext'
imgre=re.compile(reg)
html = html.decode('utf-8')
imglist = re.findall(imgre,html)
return imglist
def saveImg(imglist):
x=0
imgpath='\\testpy\\'
for imgurl in imglist:
urllib.request.urlretrieve(imgurl,imgpath+'%s.jpg'%x)
x+=1
url="http://tieba.baidu.com/p/4040087257/"
html=getHtml(url)
imgList=getImg(html)
saveImg(imgList)
print("DONE!")
【代码目的】:根据指定网址,抓取该页面的Jpg图片存入指定文件夹内
【函数解析】:(以下内容为转载整理)
import urllib.request
一、urllib模块
1.urllib.urlopen(url[,data[,proxies]])
创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远程数据。参数url表示远程数据的路径,一般是网址;参数data表示以post方式提交到url的数据(玩过web的人应该知道提交数据的两种方式:post与get。如果你不清楚,也不必太在意,一般情况下很少用到这个参数);参数proxies用于设置代理(这里不详细讲怎么使用代理,感兴趣的看客可以去翻阅Python手册urllib模块)。urlopen返回 一个类文件对象,他提供了如下方法:
urlopen返回对象提供方法:
- read() , readline() ,readlines() , fileno() , close() :这些方法的使用方式与文件对象完全一样
- info():返回一个httplib.HTTPMessage对象,表示远程服务器返回的头信息
- getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到
- geturl():返回请求的url
2.urllib.urlretrieve(url[,filename[,reporthook[,data]]])
urlretrieve方法将url定位到的html文件下载到你本地的硬盘中。如果不指定filename,则会存为临时文件。
urlretrieve()返回一个二元组(filename,mine_hdrs)
urlretrieve方法直接将远程数据下载到本地。参数filename指定了保存到本地的路径(如果未指定该参数,urllib会生成一个临时文件来保存数据);参数reporthook是一个回调函数,当连接上服务器、以及相应的数据块传输完毕的时候会触发该回调。我们可以利用这个回调函 数来显示当前的下载进度,下面的例子会展示。参数data指post到服务器的数据。该方法返回一个包含两个元素的元组(filename, headers),filename表示保存到本地的路径,header表示服务器的响应头。
3.urllib.urlcleanup()
清除由于urllib.urlretrieve()所产生的缓存
4.urllib.quote(url)和urllib.quote_plus(url)
将url数据获取之后,并将其编码,从而适用与URL字符串中,使其能被打印和被web服务器接受。
>>> urllib.quote('http://www.baidu.com') 'http%3A//www.baidu.com' >>> urllib.quote_plus('http://www.baidu.com') 'http%3A%2F%2Fwww.baidu.com'
5.urllib.unquote(url)和urllib.unquote_plus(url)
与4的函数相反。
6.urllib.urlencode(query)
将URL中的键值对以连接符&划分
这里可以与urlopen结合以实现post方法和get方法:
GET方法:
>>> import urllib >>> params=urllib.urlencode({'spam':1,'eggs':2,'bacon':0}) >>> params 'eggs=2&bacon=0&spam=1' >>> f=urllib.urlopen("http://python.org/query?%s" % params) >>> print f.read()
POST方法:
>>> import urllib >>> parmas = urllib.urlencode({'spam':1,'eggs':2,'bacon':0}) >>> f=urllib.urlopen("http://python.org/query",parmas) >>> f.read()
二、re(正则表达式)模块
1、re.match
re.match 尝试从字符串的开始匹配一个模式,如:下面的例子匹配第一个单词。
import re text = " JGood is a handsome boy, he is cool, clever, and so on... " m = re.match(r " (\w+)\s " , text) if m: print m.group(0), ' \n ' , m.group( 1 ) else : print ' not match '
re.match的函数原型为:re.match(pattern, string, flags)
第一个参数是正则表达式,这里为"(\w+)\s",如果匹配成功,则返回一个Match,否则返回一个None;
第二个参数表示要匹配的字符串;
第三个参数是标致位,用于控制正则表达式的匹配方式,如:是否区分大小写,多行匹配等等。
2、re.search
re.search函数会在字符串内查找模式匹配,只到找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
import re text = " JGood is a handsome boy, he is cool, clever, and so on... " m = re.search(r ' \shan(ds)ome\s ' , text) if m: print m.group(0), m.group( 1 ) else : print ' not search '
re.search的函数原型为: re.search(pattern, string, flags)
每个参数的含意与re.match一样。
re.match与re.search的区别:re.match只匹配字符串的开始,如果字符串开始不符合正则表达式,则匹配失败,函数返回None;而re.search匹配整个字符串,直到找到一个匹配。
3、re.sub
re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :
import re text = " JGood is a handsome boy, he is cool, clever, and so on... " print re.sub(r ' \s+ ' , ' - ' , text)
re.sub的函数原型为:re.sub(pattern, repl, string, count)
其中第二个函数是替换后的字符串;本例中为'-'
第四个参数指替换个数。默认为0,表示每个匹配项都替换。
re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。
4、re.split
可以使用re.split来分割字符串,如:re.split(r'\s+', text);将字符串按空格分割成一个单词列表。
5、re.findall
re.findall可以获取字符串中所有匹配的字符串。如:re.findall(r'\w*oo\w*', text);获取字符串中,包含'oo'的所有单词。
6、re.compile
可以把正则表达式编译成一个正则表达式对象。可以把那些经常使用的正则表达式编译成正则表达式对象,这样可以提高一定的效率。下面是一个正则表达式对象的一个例子:
text = " JGood is a handsome boy, he is cool, clever, and so on... "
regex = re.compile(r ' \w*oo\w* ' )
print regex.findall(text) # 查找所有包含'oo'的单词
print regex.sub( lambda m: ' [ ' + m.group(0) + ' ] ' , text) # 将字符串中含有'oo'的单词用[]括起来。
参考地址:
http://www.cnblogs.com/sevenyuan/archive/2010/12/06/1898075.html
http://www.cnblogs.com/sysu-blackbear/p/3629420.html
http://www.cnblogs.com/fnng/p/3576154.html