只有没有异常才枚举

Only enumerate if there is no exception

我有这样的代码:

for index, img in enumerate(soup.find_all("img")):
    try:
        print(f"[{index}] {img['data-src']}")
    except KeyError:
        pass

如您所见,我必须使用 try-except 子句,因为我正在搜索的某些图像没有 data-src 键(我无法缩小到仅包含带有 data-src 的图像的特定 div) .

我只希望枚举在没有异常的情况下递增。如何才能做到这一点?

首先仅过滤 具有 data-src 属性的 img然后 枚举:

for index, img in enumerate(x for x in soup.find_all("img") if 'data-src' in x):
    print(f"[{index}] {img['data-src']}")