使用 BeautifulSoup 从 XBRL 文件中解析 ID
Parse id from XBRL file with BeautifulSoup
我在使用 Beautifulsoup 抓取 XBRL 文件时遇到问题。
代码:
openxbrl = open(file.file_path, 'r')
readxbrl = openxbrl.read()
contextsoup = xbrlsoup.findAll('xbrli:context')
print(contextsoup)
给出如下输出(示例,有多个children)
<xbrli:context id="context0">
<xbrli:period>
<xbrli:instant>
2020-12-31
</xbrli:instant>
</xbrli:period>
我似乎无法弄清楚如何在不打印整个 contextsoup
的情况下解析上下文 ID:id="context0"
。我试图通过解析名称来打印 id:
for child in contextsoup:
pprint.pprint(child.name)
pprint.pprint(child.find('xbrli:period'))
但是没有给我id
'xbrli:context'
<xbrli:period>
<xbrli:instant>
2020-12-31
</xbrli:instant>
</xbrli:period>
如何在不打印整个 xbrl 的情况下解析 id?
id="context0"
不是元素名称的一部分,它是一个属性 (BS docs on attributes)
您可以通过将标签视为字典来访问属性值:
for context in contextsoup:
print(context['id'])
您也可以直接通过属性值查找标签。 id
属性的值在整个文档中应该是唯一的,所以你可以这样做:
soup.find(id='context0')
您还应该知道您正在使用命名空间 XML;如果您使用不同的 XBRL 报告,则不能依赖上下文标签总是被称为 xbrli:context
,因为 xbrli
位是文档定义的前缀,它为命名空间 URI。我相信 Beautiful Soup 4 确实有一些命名空间支持,但我没有使用它。
正确解析 XML 格式的 XBRL 非常复杂,我建议使用现有的 XBRL 处理器来完成它。处理 XBRL 报告的最佳方法之一是将其转换为较新的 xBRL-JSON format, and then work with it as JSON data. There are a number of tools that can do this conversion, including the open source Arelle 项目。
我在使用 Beautifulsoup 抓取 XBRL 文件时遇到问题。
代码:
openxbrl = open(file.file_path, 'r')
readxbrl = openxbrl.read()
contextsoup = xbrlsoup.findAll('xbrli:context')
print(contextsoup)
给出如下输出(示例,有多个children)
<xbrli:context id="context0">
<xbrli:period>
<xbrli:instant>
2020-12-31
</xbrli:instant>
</xbrli:period>
我似乎无法弄清楚如何在不打印整个 contextsoup
的情况下解析上下文 ID:id="context0"
。我试图通过解析名称来打印 id:
for child in contextsoup:
pprint.pprint(child.name)
pprint.pprint(child.find('xbrli:period'))
但是没有给我id
'xbrli:context'
<xbrli:period>
<xbrli:instant>
2020-12-31
</xbrli:instant>
</xbrli:period>
如何在不打印整个 xbrl 的情况下解析 id?
id="context0"
不是元素名称的一部分,它是一个属性 (BS docs on attributes)
您可以通过将标签视为字典来访问属性值:
for context in contextsoup:
print(context['id'])
您也可以直接通过属性值查找标签。 id
属性的值在整个文档中应该是唯一的,所以你可以这样做:
soup.find(id='context0')
您还应该知道您正在使用命名空间 XML;如果您使用不同的 XBRL 报告,则不能依赖上下文标签总是被称为 xbrli:context
,因为 xbrli
位是文档定义的前缀,它为命名空间 URI。我相信 Beautiful Soup 4 确实有一些命名空间支持,但我没有使用它。
正确解析 XML 格式的 XBRL 非常复杂,我建议使用现有的 XBRL 处理器来完成它。处理 XBRL 报告的最佳方法之一是将其转换为较新的 xBRL-JSON format, and then work with it as JSON data. There are a number of tools that can do this conversion, including the open source Arelle 项目。