私はPythonで基本的なWebスクレーパーをlxmlとJSONライブラリを使って書いています。以下のコードスニペットの詳細は、私は現在、CSVに書き込む方法:Python KeyErrorをうまく解決する方法(Python csv library)
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ノードを削除して再度試して行を書き込むことですが、これは面倒です(KeyErrorsを他のノードで修正しない)。
エントリが犠牲になることなく、存在しないか、データが含まれていない場合、どのようにこの状況で単一ノードを書き込むことができますか?
多くのありがとうございます。
ウェブのスクレイピングは、ほとんどの場合、常に乱雑なデータになります。以前のコードでキーを一致させる必要性を避ける方法はありますか? – Jeff
これは本当です。あなたはほぼ確実に正しいです - 私はちょうど良い、繰り返し可能な方法を見つけることができませんでした – doubleknavery
'node'は辞書ですか?もしそうなら、あなたは[get](https://docs.python.org/3.5/library/stdtypes.html#dict.get) – user3220892