我开始在 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" 的标签中的信息,并且我想要标签中的数据,在示例中为“Swahili”。所以我所做的是:
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
该程序会打印标签中包含的所有数据,但我只希望标签中包含具有正确属性的数据。我如何获得这些特定数据?