我使用lxml和JSON库用Python编写了一个基本的web scraper。下面的代码片段详细说明了我当前如何写入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节点来编写行,但这很混乱(并且不能修复其他节点的键错误)。在
在这种情况下,如果一个节点不存在或不包含任何数据,我如何在不牺牲整个条目的情况下跳过对它的写入呢?在
非常感谢。在
我有同样的问题上面,但与
DictWriter
。+因为@Jeff的回答帮了我一把。不得不稍微修改它来处理Dicts,但希望能帮助其他人:通过检查(通过
check_val
函数)该值是否存在,如果不存在,就可以避免KeyError。您还可以扩展if
语句下的逻辑,以从嵌套列表和字典中提取数据(如果这些数据可能存在或不存在),这也非常有用。在如果您必须使用这样的键,我过去在web抓取中使用的一种方法是创建一个处理错误的包装器,然后返回值。在
相关问题 更多 >
编程相关推荐