如何优雅地解决Python键错误(Python csv库)

2024-09-30 02:25:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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节点来编写行,但这很混乱(并且不能修复其他节点的键错误)。在

在这种情况下,如果一个节点不存在或不包含任何数据,我如何在不牺牲整个条目的情况下跳过对它的写入呢?在

非常感谢。在


Tags: node节点abwithopenwritefilepathnode2
2条回答

我有同样的问题上面,但与DictWriter。+因为@Jeff的回答帮了我一把。不得不稍微修改它来处理Dicts,但希望能帮助其他人:

def check_val(item_value):
    try:
        if my_data.get(item_value):
            val = something.get(item_value)
    except:
        val = None

    return val

writer.writerow({

                 'item_key' : check_val('item_value'),
                 ...
})

通过检查(通过check_val函数)该值是否存在,如果不存在,就可以避免KeyError。您还可以扩展if语句下的逻辑,以从嵌套列表和字典中提取数据(如果这些数据可能存在或不存在),这也非常有用。在

如果您必须使用这样的键,我过去在web抓取中使用的一种方法是创建一个处理错误的包装器,然后返回值。在

def get_node(name, node):
    try:
        val = node[name]
    except KeyError:
        val = 'na'
    return val

write.writerow(['allhomes',
                get_node('bathrooms', node),
                ...
               ])

相关问题 更多 >

    热门问题