我有一个xml语料库,其中一个标记名为extract<EXTRACT>
。但这个词是美组的关键词。如何提取此标记的内容。当我写entry.extract.text
时,它返回错误,当我使用entry.extract
时,将提取整个内容。
据我所知,Beautifulsoup执行标签的折叠。如果有什么方法可以克服这一点,对我也可能有帮助。
注:
目前我用以下方法解决了这个问题。
extra = entry.find('extract')
absts.write(str(extra.text))
但我想知道是否有任何方法可以使用它,就像我们使用其他标签,如
entry.tagName
最佳答案
根据BS的源代码tag.tagname
实际调用了tag.find("tagname")
引擎盖下。下面是__getattr__()
类的Tag
方法的外观:
def __getattr__(self, tag):
if len(tag) > 3 and tag.endswith('Tag'):
# BS3: soup.aTag -> "soup.find("a")
tag_name = tag[:-3]
warnings.warn(
'.%sTag is deprecated, use .find("%s") instead.' % (
tag_name, tag_name))
return self.find(tag_name)
# We special case contents to avoid recursion.
elif not tag.startswith("__") and not tag=="contents":
return self.find(tag)
raise AttributeError(
"'%s' object has no attribute '%s'" % (self.__class__, tag))
请注意,它完全基于
find()
,因此在您的案例中使用tag.find("extract")
几乎是可以的:from bs4 import BeautifulSoup
data = """<test><EXTRACT>extract text</EXTRACT></test>"""
soup = BeautifulSoup(data, 'html.parser')
test = soup.find('test')
print test.find("extract").text # prints 'extract text'
另外,您可以使用
test.extractTag.text
,但它已被弃用,我不推荐使用它。希望能有所帮助。