首页 > 解决方案 > 在 For 循环中使用它后尝试 print(i) 时未定义名称错误“i”

问题描述

我正在尝试了解网络抓取。我正在使用找到的生成器从网页中获取“基本 EPS”的位置 如何获取项目在列表中的位置?. 但是我收到此错误消息:

gen = (i for i,x in enumerate(div) if x == eps)
for i in gen: print(i)
--->  print(i)
NameError: name 'i' is not defined

我的代码是:

import requests
from bs4 import BeautifulSoup
import pprint

PAGE ="https://au.finance.yahoo.com/quote/QAN.AX/financials?p=QAN.AX"
result = requests.get(PAGE)

type(result)
source = result.text
soup = BeautifulSoup(source, 'html.parser')
div = soup.find_all('div', class_='rw-expnded')
#pprint.pprint(div)
eps = soup.find('div', title='Basic EPS')
#pprint.pprint(eps)
gen = (i for i,x in enumerate(div) if x == eps)
for i in gen: print(i)
print(i)

我对此有点困惑,因为我认为我不需要定义“i”。然后我打算在算术计算中使用“i”来查找另一个部分的位置,因此预期结果应该是 10 作为 int。

有没有人有任何提示?

编辑:添加输出diveps. print(div)具有超过最大字符数的巨大输出,但包含:

<div class="D(ib) Va(m) Ell Mt(-3px) W(215px)--mv2 W(200px) undefined" data-reactid="286" title="Basic EPS"><span class="Va(m)" data-reactid="287">Basic EPS</span></div>

print(eps)

<div class="D(ib) Va(m) Ell Mt(-3px) W(215px)--mv2 W(200px) undefined" data-reactid="286" title="Basic EPS"><span class="Va(m)" data-reactid="287">Basic EPS</span></div>

标签: python-3.x

解决方案


添加了内联注释

# below i, x are in inside a list-comprehension, so they are not avail to print in the main program
gen = (i for i,x in enumerate(div) if x == eps) 

# If any item is present in gen, only then `i` gets initialized and printed
for i in gen: print(i)

# following can give you a NameError if `i` did not get initialized before this step.
print(i)

不建议print(i)喜欢上面的内容,但是如果您想打印 gen 的最后一项,请执行以下操作

if gen:
    print(i)

或更好的选择

if gen:
    print(gen[-1])

推荐阅读