![](/img/trans.png)
[英]How to execute a class method from another class with the method passed a parameter in Python
[英]Python: Check the value of a variable passed as a parameter in another method?
與我先前的問題有關。 我正在制作一個簡單的HTML解析器,以便在Python 2.7中使用。 我想擁有多種解析類型,IE可以解析鏈接,腳本標簽,圖像等。 我正在使用HTMLParser模塊,所以我最初的想法只是為要解析的每件事創建一個單獨的類。 但這似乎很愚蠢。 有沒有一種方法可以在不創建多個類的情況下進行此操作? 我對C#更加熟悉,所以我想我只需要在init方法上傳遞一個參數來指定要解析的內容,就像在.Net中一樣,但是我似乎做的並不正確。 它行不通,而且看起來也不正確。 這是當前的工作代碼:如何將其修改為只有一個類,並且傳遞的參數指示要解析的HTML標簽的類型?
class LinksParser(HTMLParser):
def __init__(self, url):
HTMLParser.__init__(self)
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag !='a': return
for name, value in attrs:
print("Found Link --> [{0}]{1}".format(name, value))
class TagParser(HTMLParser):
def __init__(self, url, tag):
HTMLParser.__init__(self)
self.tag = tag
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag != self.tag: return
for name, value in attrs:
print("Found Tag({2}) --> [{0}]{1}".format(name, value, self.tag))
像這樣:
class MyParser(HTMLParser):
def __init__(self, url, tags):
HTMLParser.__init__(self)
self.tags = tags
req = urllib2.urlopen(url)
self.feed(req.read())
def handle_starttag(self, tag, attrs):
if tag not in self.tags: return
for name, value in attrs:
print("Found Tag --> [{0}]{1}".format(name, value))
用類似以下的方法實例化類:
p = MyParser("http://www.google.com", [ 'a', 'img' ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.