python - 无法使用 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)
解决方案
你在滥用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.
推荐阅读
- git - Github 操作,在分支上调度操作
- javascript - 点击事件打开一个带有特定项目的模式
- c - FatFS:f_findfirst 返回一个与找到的文件不对应的字符串
- docker - RabbitMq - Docker-compose - 如何修复“连接被拒绝 127.0.0.1:5672”异常
- jquery - Pharo Seaside - 如何在 html 中编辑标签后更新数据库条目
- c# - 如何获取 x:name 用于轻按手势的元素
- r - 当我尝试解析数据框中的 JSON 列时,我在 R 中不断收到错误
- html - 针对不同分辨率缩放页面
- ios - 为什么当 dequeueReusableCellWithIdentifier 发生时单元格中的 init 方法不会被调用
- c# - 远程服务器返回错误 (404) 未找到。在 system.net.httpwebrequest.getresponse()