我使用 lxml 和 JSON 库用 Python 编写了一个基本的网络抓取工具。下面的代码片段详细介绍了我当前如何写入 CSV:
with open(filepath, "ab") as f:
write = csv.writer(f)
try:
write.writerow(["allhomes",
statenum,
statesubnum,
suburbnum,
listingnum,
listingsurlstr,
'', # fill this in! should be 'description'
node["state"],
node["suburb"],
node["postcode"],
node["propertyType"],
node["bathrooms"],
node["bedrooms"],
node["parking"],
pricenode,
node["photoCount"],
node2["pricemin"],
node2["pricemax"],
node2["pricerange"]])
except KeyError, e:
try:
write.writerow(["allhomes",
statenum,
statesubnum,
suburbnum,
listingnum,
listingsurlstr,
'', # fill this in! should be 'description'
node["state"],
node["suburb"],
node["postcode"],
node["propertyType"],
'',
node["bedrooms"],
node["parking"],
pricenode,
node["photoCount"],
node2["pricemin"],
node2["pricemax"],
node2["pricerange"]])
except KeyError, e:
errorcount += 1
with open(filepath, "ab"): #
write = csv.writer(f)
write.writerow(["Error: invalid dictionary field key: %s" % e.args,
statenum,
statesubnum,
suburbnum,
listingnum,
listingsurlstr])
pass
pass
问题是,如果某个节点不存在(最常见的是 Bathrooms 节点),我必须通过用空白值替换 Bathrooms 节点来重试,或者随后放弃整行数据。我当前的方法是重试并通过删除 Bathrooms 节点来写入行,但这很困惑(并且不能修复其他节点的 KeyErrors)。
在这种情况下,如果单个节点不存在或不包含任何数据,我如何才能在不牺牲整个条目的情况下跳过写入单个节点?
非常感谢。
最佳答案
如果您必须使用这样的键,我过去在网络抓取中使用的一种方法是创建一个处理错误的包装器,然后返回值。
def get_node(name, node):
try:
val = node[name]
except KeyError:
val = 'na'
return val
write.writerow(['allhomes',
get_node('bathrooms', node),
...
])
关于python - 如何优雅地解决Python KeyError(Python csv库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38044880/