您的位置:首页 > 编程语言 > Python开发

python爬虫抓取图片

2013-07-03 14:54 465 查看
关于python爬虫一直以来是很著名的,林林总总也有很多方法,大致起来也就是一个原理。

下面我来介绍一下我用的BeautifulSoup获取的,正则获取也很简单,在这里只说一下BeautifulSoup方法,使用伯乐在线网站作为参考的例子

代码如下

#encoding:UTF-8

import urllib2,urllib,random,threading
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

class Images(threading.Thread):
def __init__(self,lock,src):
threading.Thread.__init__(self)
self.lock=lock
self.src=src
def run(self):
self.lock.acquire()
        urllib.urlretrieve(self.src,'/home/tron/Python/code/img/'+str(random.choice(range(9999))))
        print self.src+"已获取"
        self.lock.release()

def img_greb():
lock=threading.Lock()
site_url = "http://blog.jobbole.com/"
html = urllib2.urlopen(site_url).read()
soup=BeautifulSoup(html)
img=soup.findAll(['img'])
for i in img:
Images(lock,i.get('src')).start()
if __name__ == '__main__':
img_greb()


为了提高效率我使用的多线程的方法获取图片,使用啦urllib中的urlretrieve来下载图片,其中urlretrieve的参数是这样的:

urlretrieve(url,filename)

url:图片的网络路径

filename:图片的本地路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息