我在xml中有一个语料库,其中的一个标记名为extract <EXTRACT>
。但该词是Beautifulsoup中的关键字。如何提取此标签的内容。当我写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
,但已弃用,我不推荐使用。
希望能有所帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句