python - 如何优雅地解决Python KeyError(Python csv库)

标签 python json csv keyerror

我使用 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/

相关文章:

python - 使用PythonMagick将PDF转换为JPG时如何将透明背景变成白色而不是黑色

javascript - 如何使用 Joi 验证该对象键的值应该出现在另一个对象中?

asp.net - 不使用 FormsAuthentication.RedirectFromLoginPage 时如何将 Request.IsAuthenticated 设置为 true?

python - 是否可以将 "sniff"字符编码?

php - 使用 PHP 代码在 MySql 中导入 CSV 文件

MySQL加载CSV文件但没有双引号?

python - 将 Regex 与 Python 结合使用来获取 iframe src 的特定部分

Python - 如何从扩展命名空间导入父包

python - 我可以在不使用两个循环的情况下执行此任务吗?

javascript - 解析一些 JSON