码迷,mamicode.com
首页 > 编程语言 > 详细

python3 面向对象编程--类的封装和继承

时间:2018-09-24 13:52:51      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:name   ima   lin   find   image   try   obj   list   read   

#python3
import re
from urllib import request
import os

class PosterSpider(object):
     def __init__(self, path=‘./‘):
           self.path = path

#the entry of this process

     def getStart(self, url):
           page = self.reqPage(url)

           page = page.decode(‘utf-8‘)

           for mvname,mvurl in self.getMvInfo(page):
                self.save2File(mvname,mvurl)

           nexturl = self.getNextpage(page)
           if nexturl:
               self.getStart(nexturl)


#request the page
      def reqPage(self, url):
           response = request.urlopen(url)
           if response.code == 200:
              page = response.read()
              return page

#get the fname and url for each mv
       def getMvInfo(self, page):
             urllist = re.findall(r‘<img.*alt="(.*?)".*src="(.*?)"‘,page)
             return urllist

#get next page url
       def getNextpage(self, page):
             url = ‘https://movie.douban.com/top250‘
             nexturlraw = re.findall(r‘<link rel="next" href="(.*?)"‘,page)
             if nexturlraw:
                nexturllast = url + nexturlraw[0]
                return nexturllast

#save img to file
    def save2File(self, fname, url):
          image = self.reqPage(url)
          fname = fname + ‘.jpg‘
          fpath = os.path.join(self.path,fname)
          with open(fpath,‘wb‘) as f:
                  f.write(image)

if __name__ == ‘__main__‘:
    url = ‘https://movie.douban.com/top250‘
    spider = PosterSpider(‘img‘)
    spider.getStart(url)

python3 面向对象编程--类的封装和继承

标签:name   ima   lin   find   image   try   obj   list   read   

原文地址:https://www.cnblogs.com/hixiaowei/p/9695253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!