【问题标题】:python3: Read json file from urlpython3:从url读取json文件
【发布时间】:2017-02-08 09:01:03
【问题描述】:

在python3中,我想加载this_file,这是一个json格式。

基本上,我想做一些类似[伪代码]的事情:

>>> read_from_url = urllib.some_method_open(this_file)
>>> my_dict = json.load(read_from_url)
>>> print(my_dict['some_key'])
some value

【问题讨论】:

  • 您实际尝试了什么?您的伪代码似乎接近可行的东西......
  • 这就是问题所在,可以工作...但到目前为止我做不到 =/

标签: python json url


【解决方案1】:

所以您希望能够通过输入键引用特定值?如果我认为我知道您想做什么,这应该可以帮助您入门。您将需要库 urllib2、json 和 bs4。只需 pip 即可轻松安装它们。

import urllib2
import json
from bs4 import BeautifulSoup

url = urllib2.urlopen("https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json")
content = url.read()
soup = BeautifulSoup(content, "html.parser")
newDictionary=json.loads(str(soup))

我用了一个常用的url来练习。

【讨论】:

  • urllib2 在 python3 中不可用。最好我只想使用内置库
  • 啊,好吧 urllib 应该做同样的事情吧?试试看。
  • 不错。只需将urllib2.urlopen 更改为urllib.request.urlopen。谢谢。
  • 没问题!很高兴它起作用了, requests 也是一个不错的库(请参阅下面的答案)该库中有一些很棒的功能。
【解决方案2】:

你很亲密:

import requests
import json
response = json.loads(requests.get("your_url").text)

【讨论】:

    【解决方案3】:

    只需使用 json 和 requests 模块:

    import requests, json
    
    content = requests.get("http://example.com")
    json = json.loads(content.content)
    

    【讨论】:

    • 我收到TypeError: the JSON object must be str, not 'bytes'
    【解决方案4】:

    或者使用标准库:

    from urllib.request import urlopen
    import json
    
    data = json.loads(urlopen(url).read().decode("utf-8"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 2020-03-17
      • 1970-01-01
      • 2021-03-23
      相关资源
      最近更新 更多