【问题标题】:How save the "for loop" json output to a variable without changing its format?如何将“for循环”json输出保存到变量而不改变其格式?
【发布时间】:2018-03-06 04:53:52
【问题描述】:

我正在尝试从网站上抓取一些数据,结果是 json 格式,但我还必须对该 json 数据进行一些操作,所以如果我将 for 循环的 json 格式输出保存到列表中,那么格式将会改变而且我将无法执行某些操作,有什么方法可以在不更改格式的情况下存储输出?

import requests as tt
from bs4 import BeautifulSoup
import json

get_url=tt.get("https://in.pinterest.com/search/pins/?rs=ac&len=2&q=batman%20motivation&eq=batman%20moti&etslf=5839&term_meta[]=batman%7Cautocomplete%7Cundefined&term_meta[]=motivation%7Cautocomplete%7Cundefined")
soup=BeautifulSoup(get_url.text,"html.parser")
er=[]
select_css=soup.select("script#jsInit1")[0]
for i in select_css:
    er.append(json.loads(i))

【问题讨论】:

  • 你试过用.join()
  • 是的,我试过了。
  • TypeError:序列项 0:预期 str 实例,找到字典
  • 可以分享select_css的内容吗?

标签: python json python-2.7 python-3.x for-loop


【解决方案1】:

好的,所以我想将输出保存在任何变量中,然后我将 select_css 传递给一个函数,而不是附加我返回数据,然后给出对该函数的引用(闭包)并将返回的输出用于一些操作.

import requests as tt
from bs4 import BeautifulSoup
import json

get_url=tt.get("https://in.pinterest.com/search/pins/?rs=ac&len=2&q=batman%20motivation&eq=batman%20moti&etslf=5839&term_meta[]=batman%7Cautocomplete%7Cundefined&term_meta[]=motivation%7Cautocomplete%7Cundefined")
soup=BeautifulSoup(get_url.text,"html.parser")
er=[]
select_css=soup.select("script#jsInit1")[0]


def hello(x):
    for i in x:
        return json.loads(i)

desired_variable=hello(select_css)

print(desired_variable['tree']['data']['results'][2]['images']['orig']['url'])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多