Python Beauty Soup-XML解析-属性错误异常(处理空值)
我有以下代码:Python Beauty Soup-XML解析-属性错误异常(处理空值),python,pandas,beautifulsoup,xml-parsing,Python,Pandas,Beautifulsoup,Xml Parsing,我有以下代码: from bs4 import BeautifulSoup import pandas as pd import sqlite3 conn = sqlite3.connect('test.db') inputFile = open("test.xml","r") data = BeautifulSoup(inputFile,'xml') stop_points = data.find_all('Location') l = [] df
from bs4 import BeautifulSoup
import pandas as pd
import sqlite3
conn = sqlite3.connect('test.db')
inputFile = open("test.xml","r")
data = BeautifulSoup(inputFile,'xml')
stop_points = data.find_all('Location')
l = []
df = pd.DataFrame(columns=['Id','One','Two','Three','Four','Five'])
pos= 0
for stop in stop_points:
l.append(stop.get('id'))
l.append(stop.find('One').text)
l.append(stop.find('Two').text)
l.append(stop.find('Three').text)
l.append(stop.find('Four').text)
l.append(stop.find('Five').text)
df.loc[pos] = l
l = []
pos+=1
print(df)
df.to_sql('Location',conn,if_exists='replace',index=False)
但是,在某些情况下,“Location”并没有包含所有元素(“一”、“二”、“三”、“四”或“五”)。当脚本迭代到不包含所有这些元素的位置时,将引发属性错误异常:
Exception has occurred: AttributeError
'NoneType' object has no attribute 'text'
因此,我认为在尝试将“.text”附加到列表之前需要进行状态检查。然而,我并不想添加五个“如果”语句,因为这不是很优雅
以下是XML文件的示例,以供参考:
<Location id="00000">
<Translation>
<One>111111</One>
<Two>222222</Two>
<Four>-5.0</Four>
<Five>50.0</Five>
</Translation>
</Location>
<Location id="11111">
<Translation>
<One>111111</One>
<Two>222222</Two>
<Three>-5.0</Three>
<Five>50.0</Five>
</Translation>
</Location>
<Location id="22222">
<Translation>
<One>111111</One>
<Two>222222</Two>
</Translation>
</Location>
111111
222222
-5.0
50
111111
222222
-5.0
50
111111
222222
假设您的html如下所示:
locations = """
<locations>
<Location id="00000">
<Translation>
<Easting>111111</Easting>
<Northing>222222</Northing>
<Longitude>-5.0</Longitude>
<Latitude>50.0</Latitude>
</Translation>
</Location>
<Location id="00001">
<Translation>
<Easting>4444</Easting>
<Northing>5555</Northing>
<Longitude>-6.0</Longitude>
<Latitude>70.0</Latitude>
</Translation>
</Location>
</locations>
"""
stop_points = data.select('location')
columns=['Id','One','Two','Three','Four']
rows = []
for s in stop_points:
row = []
row.append(s['id'])
row.extend(s.text.strip().split('\n'))
rows.append(row)
pd.DataFrame(rows,columns=columns)
应输出:
Id One Two Three Four
0 00000 111111 222222 -5.0 50.0
1 00001 4444 5555 -6.0 70.0
迭代遍历参数列表,并将单个
if
语句置于状态。您能否在inputFile
中发布xml的代表性示例?另外,由于您处理的是xml,您可能希望使用像lxml这样的xml解析器进行解析,并使用xpath。示例xml不包含任何、、
。这是故意的吗?对不起,我没有发现我明显的错误。现在我已经更正了XML示例,以便更好地说明用例。