gpt4 book ai didi

python - iterparse 解析一个字段失败,而其他类似的没问题

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:48 26 4
gpt4 key购买 nike

我使用 Python 的 iterparse解析 nessus 扫描的 XML 结果(.nessus 文件)。对意外记录的解析失败,但相似的记录已被正确解析。

XML 文件的一般结构是很多记录,如下所示:

<ReportHost>
<ReportItem>
<foo>9.3</foo>
<bar>hello</bar>
</ReportItem>
<ReportItem>
<foo>10.0</foo>
<bar>world</bar>
</ReportHost>
<ReportHost>
...
</ReportHost>

换句话说,很多主机 ( ReportHost ) 有很多项目要报告 ( ReportItem ),而后者有几个特征 ( foo , bar )。我将着眼于为每个项目生成一行,及其特征。

解析在文件中间的一个简单行中失败( foo 在这种情况下为 cvss_base_score )

<cvss_base_score>9.3</cvss_base_score>

同时分析了约 200 行类似的行,没有问题。

下面是相关的代码——它设置了上下文标记(inReportHostinReportEvent,它们告诉我我在 XML 文件的结构中的什么位置,并分配或打印一个值,具体取决于上下文)

import xml.etree.cElementTree as ET
inReportHost = False
inReportItem = False

for event, elem in ET.iterparse("test2.nessus", events=("start", "end")):
if event == 'start' and elem.tag == "ReportHost":
inReportHost = True
if event == 'end' and elem.tag == "ReportHost":
inReportHost = False
elem.clear()
if inReportHost:
if event == 'start' and elem.tag == 'ReportItem':
inReportItem = True
cvss = ''
if event == 'start' and inReportItem:
if event == 'start' and elem.tag == 'cvss_base_score':
cvss = elem.text
if event == 'end' and elem.tag == 'ReportItem':
print cvss
inReportItem = False

cvss有时具有 None 值(在 cvss = elem.text 赋值之后),即使相同的条目已在文件的早期正确解析。

如果我在作业下面添加一些内容

if cvss is None: cvss = "0"

然后更多的解析cvss为它们分配适当的值(还有一些是 None)。

服用<ReportHost>...</reportHost>时这导致错误的解析并通过程序运行它 - 它工作正常(即 cvss 按预期分配了 9.3)。

我在我的代码中犯了错误的地方迷路了,因为有大量类似的记录,一些预先处理正确而另一些 - 不正确(一些记录是相同的,但仍然以不同的方式处理)。我也找不到关于失败记录的任何特别之处 - 前后相同的记录都可以。

最佳答案

来自iterparse() docs :

Note: iterparse() only guarantees that it has seen the “>” character of a starting tag when it emits a “start” event, so the attributes are defined, but the contents of the text and tail attributes are undefined at that point. The same applies to the element children; they may or may not be present. If you need a fully populated element, look for “end” events instead.

删除 inReport* 变量并在完全解析后仅在“结束”事件上处理 ReportHost。使用 ElementTree API 从当前 ReportHost 元素获取必要的信息,例如 cvss_base_score

为了保持内存,做:

import xml.etree.cElementTree as etree

def getelements(filename_or_file, tag):
context = iter(etree.iterparse(filename_or_file, events=('start', 'end')))
_, root = next(context) # get root element
for event, elem in context:
if event == 'end' and elem.tag == tag:
yield elem
root.clear() # preserve memory

for host in getelements("test2.nessus", "ReportHost"):
for cvss_el in host.iter("cvss_base_score"):
print(cvss_el.text)

关于python - iterparse 解析一个字段失败,而其他类似的没问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14670792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com