python里爬取页面中图片命令

来源:互联网 发布:淘宝订单评价过期 编辑:程序博客网 时间:2024/04/26 11:10
python代码,获取网页中图片,并重新编码为0,1,2,。。。保存到本地。
#coding=utf-8import urllibimport redef getHtml(url):    page = urllib.urlopen(url)    html = page.read()    return htmldef getImg(html):    reg = r'src="(.+?\.jpg)" pic_ext'    imgre = re.compile(reg)    imglist = re.findall(imgre,html)    x = 0    for imgurl in imglist:        urllib.urlretrieve(imgurl,'%s.jpg' % x)        x+=1html = getHtml("http://tieba.baidu.com/p/2460150866")print getImg(html)
urllib.urlopen()方法用于打开一个URL地址
read()方法用于读取URL上的数据,向getHtml()函数传递一个网址,并把整个页面下载下来。
getImg()函数,用于在获取的整个页面中筛选需要的图片连接

re.compile() 可以把正则表达式编译成一个正则表达式对象.

re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。

转自:http://www.cnblogs.com/fnng/p/3576154.html
常用命令总结

Python通过re模块提供对正则表达式的支持。使用re的一般步骤是先使用re.compile()函数,将正则表达式的字符串形式编译为Pattern实例,然后使用Pattern实例处理文本并获得匹配结果(一个Match实例),最后使用Match实例获得信息,进行其他的操作。

举一个简单的例子,在寻找一个字符串中所有的英文字符:

import repattern = re.compile('[a-zA-Z]')result = pattern.findall('as3SiOPdj#@23awe')print result# ['a', 's', 'S', 'i', 'O', 'P', 'd', 'j', 'a', 'w', 'e']
参考文献:http://zhidao.baidu.com/link?url=IgVsryMGpucqMs9ev7abFRwyjFpaDE2Ys8L1OlWojNgm5pv_C7BPesu5Jl7PX45PQGJNY7J5oq4SY7EOHP5un8fEW8vVebu88XCmCLkmnW_

0 0
原创粉丝点击