我开始使用 Python 中的 HTMLParser 从网站中提取数据。
我得到了我想要的一切,除了两个 HTML 标签内的文本。
以下是 HTML 标签的示例:
<a href="http://wold.livingsources.org/vocabulary/1" title="Swahili" class="Vocabulary">Swahili</a>
还有其他以 开头的标签。他们有其他属性和值,因此我不想拥有他们的数据:
<a href="http://wold.livingsources.org/contributor#schadebergthilo" title="Thilo Schadeberg" class="Contributor">Thilo Schadeberg</a>
该标签是表中的嵌入标签。我不知道这与其他标签是否有什么区别。
我只想要一些名为“a”且属性为 class="Vocabulary" 的标签中的信息,并且我想要标签内的数据,在示例中它将是“斯瓦希里语”。
所以我所做的是:
class AllLanguages(HTMLParser):
'''
classdocs
'''
#counter for the languages
#countLanguages = 0
def __init__(self):
HTMLParser.__init__(self)
self.inLink = False
self.dataArray = []
self.countLanguages = 0
self.lasttag = None
self.lastname = None
self.lastvalue = None
#self.text = ""
def handle_starttag(self, tag, attr):
#print "Encountered a start tag:", tag
if tag == 'a':
for name, value in attr:
if name == 'class' and value == 'Vocabulary':
self.countLanguages += 1
self.inLink = True
self.lasttag = tag
#self.lastname = name
#self.lastvalue = value
print self.lasttag
#print self.lastname
#print self.lastvalue
#return tag
print self.countLanguages
def handle_endtag(self, tag):
if tag == "a":
self.inlink = False
#print "".join(self.data)
def handle_data(self, data):
if self.lasttag == 'a' and self.inLink and data.strip():
#self.dataArray.append(data)
#
print data
该程序打印标签中包含的所有数据,但我只希望标签中包含的数据具有正确的属性。
我如何获得这些具体数据?