13-爬取百度貼吧中的圖片(python+xpath)

來源:互聯網
上載者:User

標籤:clear   http   url編碼   ref   內容   img   XML   百度貼吧   name   

通過xpath分析頁面,爬取頁面中的圖片:

#_*_ coding: utf-8 _*_‘‘‘Created on 2018年7月15日@author: sssfunction: 使用xpath還處理爬取的資料‘‘‘from lxml import etreeimport urllibfrom pip._vendor.distlib.compat import raw_inputfrom asyncio.tasks import sleepclass Spider:    def __init__(self):        self.tiebaName = raw_input(‘請輸入需要爬去的貼吧的名字‘)        self.beginPage = int(raw_input(‘其輸入起始頁‘))        self.endPage = int(raw_input(‘請輸入終止頁‘))                self.url = ‘http://tieba.baidu.com/f‘        self.ua_header = {‘User-Agent‘: ‘Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1 Trident/5.0;‘}                #圖片編號        self.userName = 1        #計算爬取頁    def tiebaSpider(self):          for page in range(self.beginPage, self.endPage + 1):            pn = (page - 1) * 50 #url中的page number            word = {‘pn‘: pn, ‘kw‘: self.tiebaName}                    word = urllib.parse.urlencode(word ) #轉化為url編碼格式            myUrl = self.url + ‘?‘ + word                         #調用頁面處理函數load_Page            #並擷取頁面的所有文章連結            links = self.loadPage(myUrl)                #開始抓取每個首頁所有樓主發帖的標貼串連     def loadPage(self, url ):                req = urllib.request.Request(url, headers=self.ua_header)        html = urllib.request.urlopen(req).read()                    #解析html為html文檔        selector = etree.HTML(html)                    #抓取當前頁面的所有文章的url的後部分,也就是文章的編號        # http://tieba.baidu.com/p/4884069807裡的 “p/4884069807”        links = selector.xpath(‘//div[@class="threadlist_lz clearfix"]/div/a/@href‘)                #links類型為etreeElementString列表        #遍曆列表,並且合并成一個文章地址,調用圖片處理函數LoadImage        for link in links:            link = ‘http://tieba.baidu.com‘ + link            self.loadImages(link )           #抓取每個首頁中對應的每個樓主的發布詳細頁面        def loadImages(self, link ):        req = urllib.request.Request(link, headers= self.ua_header)        html = urllib.request.urlopen(req).read()                selector = etree.HTML(html)                #擷取這個文章裡的所有圖片的src路徑        imagesLinks = selector.xpath(‘//img[@class="BDE_Image"]/@src‘)                #擷取圖片路徑,下載儲存        for imagesLink in imagesLinks:            self.writeImages(imagesLink)                    print(‘完成所有下載!‘)            #儲存頁面中的圖片    def writeImages(self, imagesLink):        """                    將Images裡的二進位內容存入到userNname檔案中        """        print(imagesLink)                #通過圖片串連擷取圖片內容:        images = urllib.request.urlopen(imagesLink).read()                print(‘正在隱藏檔%d...‘ % self.userName)                #寫入檔案:        with open(‘./images/‘ + str(self.userName) + ‘.png‘, ‘wb‘) as f:  #存入也該項目同級的images檔案夾中            f.write(images)                #計數器加一        self.userName += 1          if __name__ == ‘__main__‘:    mySpider = Spider()    mySpider.tiebaSpider()   

  

13-爬取百度貼吧中的圖片(python+xpath)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.