python-3.x - 在 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。
有没有人有任何提示?
编辑:添加输出div
和eps
.
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>
解决方案
添加了内联注释
# 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])
推荐阅读
- android - ADB pm grant 不适用于 Android 10 上的某些权限
- c# - 如何从自定义 Nuget 包中确定要使用的平台配置?
- machine-learning - Logistic回归中的多重共线性检查(插管测试)?
- ibm-mq - 更改频道名称
- ios - 如何安全地从 Xcodes 编译源中删除文件?
- c# - Telegram Bot 停止并在 mscorlib.dll 中发生“System.AggregateException”类型的未处理异常
- powershell - 在频道中获取/创建消息的问题
- mysql - IntelliJ Idea IDE 检测 SQL 字符串仅在 SQL 语句是基本字符串时有效
- c# - 在 C# MVC 中从内存流创建 excel 时忽略警告
- javascript - 是什么导致了我的网站上的额外边距,为什么它的宽度不是全部?