【发布时间】:2016-06-27 01:50:40
【问题描述】:
我使用 lxml 和 JSON 库在 Python 中编写了一个基本的网络爬虫。下面的代码 sn-p 详细说明了我目前如何写入 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
问题在于,如果某个节点不存在(最常见的是浴室节点),我必须通过将浴室节点替换为空白值来重试,或者随后放弃整行数据。我目前的方法是通过删除浴室节点重试并写入该行,但这很混乱(并且不能修复其他节点的 KeyErrors)。
在这种情况下,如果单个节点不存在或不包含任何数据,我如何在不牺牲整个条目的情况下跳过写入?
非常感谢。
【问题讨论】:
-
任何大小的网络抓取几乎总是导致数据混乱,似乎。有没有一种方法可以避免在代码前面的某个位置匹配键的需要?
-
哈哈这是真的。你几乎肯定是对的 - 我只是找不到一个好的、可重复的方法来做到这一点
-
node是字典吗?如果是这样,您可以使用get