首页 > 解决方案 > 无法使用 Enumerate 提供递增整数 ID

问题描述

我正在编写一个脚本,该脚本将使用 Beautiful Soup 抓取网页。该页面包含许多我想要解析的 div 以获取各种信息。对于每个 div,我将创建一个字典。该字典包含我想要从页面中提取的各种内容的键值对。然后我将每个字典放入一个列表中。

作为我脚本的一部分,我想在每个 div 中分配一个递增的整数 id (0, 1, 2) 作为键值对。除了提供此 ID 的代码外,我的脚本中的所有内容都正常工作。我正在使用的虚拟数据有 12 个 div。该脚本生成 12 个字典,但对于每个字典,id = 11。

下面是我正在使用的代码。我已经注释掉了其中一个函数的大部分,因为它似乎与这个特定问题无关。我怀疑问题出在我的“count_headers”函数中,但我认为我正确使用了枚举。

def extract_metadata(divs):

    header_dict_list = []

    for div in divs:
        header_dict = {}

        header_index = enumerate(divs,0)

        def count_headers(div):
            for num, div in header_index:
                header_id = num
                header_dict['id'] = header_id

        def extract_header_stuff(div):

            # Bunch of stuff happens here to pull out different pieces of information and populate the header_dict for each div. 

        extract_header_stuff(div)

        count_headers(div)

        header_dict_list.append(header_dict)

    print (header_dict_list)

标签: pythonpython-3.xweb-scrapingbeautifulsoupenumerate

解决方案


你在滥用enumerate. 正确的代码应该是:

    for id, div in enumerate(divs) :
        header_dict = {id: id}

        # You probably don't want to define `extract_header_stuff` in the loop
        # either.

推荐阅读