我开始使用 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”且属性为“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
程序打印标签中包含的所有数据,但我只想要标签中包含的具有正确属性的数据。 我如何获得这些特定数据?
最佳答案
看起来你忘记在 handle_starttag
中默认设置 self.inLink = False
:
from HTMLParser import HTMLParser
class AllLanguages(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.inLink = False
self.dataArray = []
self.countLanguages = 0
self.lasttag = None
self.lastname = None
self.lastvalue = None
def handle_starttag(self, tag, attrs):
self.inLink = False
if tag == 'a':
for name, value in attrs:
if name == 'class' and value == 'Vocabulary':
self.countLanguages += 1
self.inLink = True
self.lasttag = tag
def handle_endtag(self, tag):
if tag == "a":
self.inlink = False
def handle_data(self, data):
if self.lasttag == 'a' and self.inLink and data.strip():
print data
parser = AllLanguages()
parser.feed("""
<html>
<head><title>Test</title></head>
<body>
<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 href="http://wold.livingsources.org/vocabulary/2" title="English" class="Vocabulary">English</a>
<a href="http://wold.livingsources.org/vocabulary/2" title="Russian" class="Vocabulary">Russian</a>
</body>
</html>""")
打印:
Swahili
English
Russian
另外,看看:
希望对您有所帮助。
关于Python:使用 html 解析器提取特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16773583/