我开始使用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
该程序会打印出所有包含在标签中的数据,但我只想要那些包含正确属性的标签中的数据。如何获取这些特定的数据?