python3 面向对象编程--类的封装和继承
Posted littlevigra
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python3 面向对象编程--类的封装和继承相关的知识,希望对你有一定的参考价值。
#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 面向对象编程--类的封装和继承的主要内容,如果未能解决你的问题,请参考以下文章
Python3-2020-测试开发-20- 面向对象之封装,继承,多态