首页 > 解决方案 > 无法根据字典中的项目获取值

问题描述

我在 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)

标签: pythonpython-3.xweb-scrapingbeautifulsoup

解决方案


有很多方法可以做到这一点。您使用变量的想法是正确的;你只需要弄清楚什么时候改变它。一种简单的方法是在进入循环之前分配“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)

推荐阅读