python 爬蟲批量下載圖片__python

來源:互聯網
上載者:User

今天加班啊,苦啊。。

無聊,用python寫了一個抓圖片的爬蟲,感覺很不錯啊,哈哈

先貼上代碼:(python 版本:2.7.9)

__author__ = 'bloodchilde'import  urllibimport urllib2import  reimport osclass Spider:    def __init__(self):        self.siteUrl="http://sc.chinaz.com/biaoqing/"        self.user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko'        self.headers = { 'User-Agent' : self.user_agent }    def getPage(self,pageIndex):        url = self.siteUrl+"index_"+str(pageIndex)+".html"        request = urllib2.Request(url,headers = self.headers)        response = urllib2.urlopen(request)        return response.read().decode("utf-8")    def getContents(self,pageIndex):        page = self.getPage(pageIndex)        pattern = re.compile('''<div.*?class='num_1'.*?>.*?<p>.*?<a.*?href='.*?'.*?target='_blank'.*?title='(.*?)'.*?><img.*?src2="(.*?)".*?>.*?</a>.*?</p>.*?</div>''',re.S)        items = re.findall(pattern,page)        contents=[]        for item in items:            contents.append([item[0],item[1]])        return contents    def mk_dir(self,path):        isExisist = os.path.exists(path)        if not isExisist:            os.makedirs(path)            return True        else:            return False    def downImage(self,url,dirname):        imageUrl = url        request = urllib2.Request(imageUrl,headers = self.headers)        response = urllib2.urlopen(request)        imageContents = response.read()        urlArr = imageUrl.split(u"/")        imageName = str(urlArr[len(urlArr)-1])        print imageName        path = u"C:/Users/bloodchilde/Desktop/image_python/"+dirname        self.mk_dir(path)        imagePath = path+u"/"+imageName        f = open(imagePath, 'wb')        f.write(imageContents)        f.close()    def downLoadAllPicture(self,PageIndex):        contents = self.getContents(PageIndex)        for list in contents:            dirname = list[0]            imageUrl = list[1]            self.downImage(imageUrl,dirname)demo = Spider()for page in range(3,100):    demo.downLoadAllPicture(page)

效果如下:






下載這麼多圖片,瞬間搞定,下面來分析一下程式:


首先,我的目標網頁是:

http://sc.chinaz.com/biaoqing/index_3.html

程式功能是到這個網頁下載表情圖片

程式思路:

1,擷取網頁的源碼資訊

2,解析源碼擷取要下載的圖片的URL(正則處理)

3,重新置放url向這個圖片的url發起請求擷取url的資訊,這個url資訊其實就是圖片內容contents

4,通過上面擷取的圖片的URL還可以擷取圖片的名稱(帶尾碼名) imageName

5,在本地建立檔案以擷取的imageName命名,將內容contents寫進檔案即可


開啟http://sc.chinaz.com/biaoqing/index_3.html,查看源碼,找到要處理的程式碼片段如下:



對應的正則是:

'''<div.*?class='num_1'.*?>.*?<p>.*?<a.*?href='.*?'.*?target='_blank'.*?title='(.*?)'.*?><img.*?src2="(.*?)".*?>.*?</a>.*?</p>.*?</div>'''

我們要從程式碼片段中擷取title和src2,title作為檔案夾名,src2作為靶心圖表片URL

是不是感覺很簡單啊。。。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.