python爬虫類捕まえ画像

1200 ワード

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:画像のローカルパス