【发布时间】:2018-07-21 17:58:04
【问题描述】:
我正在尝试将以下 XML 转换为 CSV。问题是每个条目可能没有值,因此它返回NoneType。例如,在下面显示的 XML 中,并非每个“条目”都有一个“规则”。
如果发生这种情况,我希望 CSV 文件不包含任何内容或包含通用值,例如“EMPTY”。我希望 CSV 文件看起来像这样:
domain serial seqno rule
1 43434343434 1 21
1 43434343434 1 21
1 43434343434 1 EMPTY
通过使用下面显示的列表理解,我能够避免 NoneType 错误。但是,我似乎需要一些帮助来格式化 CSV 中的数据。
rows = [cleanhtml(str(entry))
for entry in soup.find_all("entry")
if entry.find(header_list[counter]) is not None]
#!/usr/bin/env python3
import csv
import re
from bs4 import BeautifulSoup
html_results='''<response status="success"><result>
<job>
<tenq>09:48:24</tenq>
<tdeq>09:48:24</tdeq>
<tlast>18:00:00</tlast>
<status>FIN</status>
<id>5955</id>
<cached-logs>1118</cached-logs>
</job>
<log>
<logs count="100" progress="100">
<entry logid="4343">
<domain>1</domain>
<serial>43434343434</serial>
<seqno>0</seqno>
<actionflags>0x0</actionflags>
<type>EXAMPLE</type>
<subtype>EXAMPLE</subtype>
<config_ver>0</config_ver>
<src>1.1.1.1</src>
<dst>1.1.1.1</dst>
<rule>Rule 21</rule>
</entry>
<log>
<entry logid="4343">
<domain>1</domain>
<serial>43434343434</serial>
<seqno>0</seqno>
<actionflags>0x0</actionflags>
<type>EXAMPLE</type>
<subtype>EXAMPLE</subtype>
<config_ver>0</config_ver>
<src>1.1.1.1</src>
<dst>1.1.1.1</dst>
<rule>Rule 21</rule>
</entry>'''
def cleanhtml(raw_html):
tags = re.compile('<.*?>')
cleantext = re.sub(tags, '', raw_html)
return cleantext
soup = BeautifulSoup(html_results, 'html.parser')
header_list = ['domain',"serial","seqno","actionflags","type","subtype","config_ver","src","dst","rule"]
query_results = open("query_results.csv","w")
csvwriter = csv.writer(query_results)
csvwriter.writerow(header_list)
num_of_logs = soup.find("logs").get("count")
counter = 0
rows = [cleanhtml(str(entry)) for entry in soup.find_all("entry") if entry.find(header_list[counter]) is not None]
csvwriter.writerows(rows)
query_results.close()
【问题讨论】:
-
既然您知道如何处理
None条目,那么您的输出是什么?
标签: python xml csv python-3.5