先把網頁資料撈回來吧!基於這個理由,就先寫了簡單的類別~
花了不少時間,終於搞點像樣的東西了...像我這樣的python新手寫這麼爛的類別Code真是丟人現眼QQ
物件導向也不是很熟,得多學學了!
總之,先從urllib開始吧!
這樣的類別問題真多,甚至出現一個Bug,天色已深,先用個替代方案,明天再看看囉@@
﹝做這樣的類別有意義嗎?﹞
問題和待改進:
1.有一個已知BUG
2.呼叫一次方法會重新擷取資料﹝傳送request﹞,應該修改要修改一下!
#! /usr/bin/env python
#-*- coding: utf-8 -*-
import urllib.request
class MyUrlAnaluzeRequest():
def __init__(self, targetUrl=""):
self.targetUrl = targetUrl
self.urlobj = ""
def targetUrl(self, setUrl=""):
self.targetUrl = setUrl
def _urlopen(self):
try:
self.urlobj = urllib.request.urlopen( self.targetUrl )
except:
print("urlopen error!")
def _urlclose(self):
self.urlobj.close()
def getUrl(self):
self._urlopen()
url = self.urlobj.geturl()
self._urlclose()
return url
def getFileno(self):
self._urlopen()
fileno = self.urlobj.fileno()
self._urlclose()
return fileno
def getCode(self):
self._urlopen()
getcode = self.urlobj.getcode()
self._urlclose()
return getcode
def getAllHTML(self):
self._urlopen()
data = self.urlobj.read()
self._urlclose()
return data
def getInfo(self):
self._urlopen()
info = self.urlobj.info()
self._urlclose()
return info
if __name__ == "__main__":
targetUrl = "https://www.google.com.tw"
UrlRequestObj = MyUrlAnaluzeRequest()
#UrlRequestObj.targetUrl( targetUrl ) # TypeError: 'str' object is not callable
UrlRequestObj.__init__( targetUrl )
#print ( UrlRequestObj.getCode() )
#print ( UrlRequestObj.getUrl() )
#print ( UrlRequestObj.getInfo() )
#print ( UrlRequestObj.getFileno() )
#print ( UrlRequestObj.getAllHTML() )