python - 无法根据字典中的项目获取值
问题描述
我在 python 中编写了一个脚本来获取该项目及其在字典中的值。当我运行我的脚本时,它确实以错误的方式获取它,我的意思不是以我希望的方式。
我现在得到的结果是:
{'4194813.75690': 'foo', '4194813.75691': 'foo'}
但是,我希望拥有:
{'4194813.75690': 'foo', '4194813.75691': 'bar'}
在name
属性中,这部分4194813
总是稳定的,但是这部分是动态变化的,所以除了我在下面尝试过.75691
的之外,我不能使用任何合适的标志。.startswith()
这是脚本:
import requests
from bs4 import BeautifulSoup
url = "https://www.electricityregistry.co.nz/bin_public/jadehttp.dll?MariaWebR"
res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
formdata = {}
for items in soup.select("[name='JadeForm'] input"):
if items.get("name").startswith('4194813'):
item = items.get("name")
val = "foo" #how to change it to "bar" in the second iteration
formdata[item] = val
print(formdata)
解决方案
有很多方法可以做到这一点。您使用变量的想法是正确的;你只需要弄清楚什么时候改变它。一种简单的方法是在进入循环之前分配“foo” val
,使用它来分配您的字典值,然后val
在使用后更改为“bar”。
val = "foo"
for items in soup.select("[name='JadeForm'] input"):
if items.get("name").startswith('4194813'):
item = items.get("name")
formdata[item] = val
val = "bar"
另一种方法是将值放入列表中,在列表上创建一个迭代器,然后用于next()
从迭代器中获取下一个值。这是一种更通用的方法,可以用于任意数量的项目,而不仅仅是两个。
val = iter(["foo", "bar"])
for items in soup.select("[name='JadeForm'] input"):
if items.get("name").startswith('4194813'):
item = items.get("name")
formdata[item] = next(val)
推荐阅读
- javascript - laravel api token - 数据不显示
- ajax - 重新加载或使用旧输入数据提交表单后重定向到同一个 ajax 页面
- python - Dask:一个工作人员在多个节点上的作业,仅在一个节点上运行
- ios - 如何访问 Notification(基础类)而不是我的(名为 Notification 的自定义类)?
- koin - 无法运行示例测试 Koin
- java - StreamingResponseBody 返回空文件
- python - Visual Studio Code 不会加载 tkinter 包
- ionic-framework - 如何使用 Ionic 拍摄全景照片?
- python - 如何有效地改变matplotlib中许多重叠圆圈的颜色
- javascript - Window.location.replace 不会重定向我给定的网址