Python Beautiful Soup如何将JSON解码为`dict`?

时间:2022-11-29 13:11:02

I'm new to BeautifulSoup in Python and I'm trying to extract dict from BeautifulSoup.

我是Python的BeautifulSoup的新手,我正试图从BeautifulSoup中提取dict。

I've used BeautifulSoup to extract JSON and got beautifulsoup.beautifulsoup variable soup.

我用BeautifulSoup提取JSON并获得了beautifulsoup.beautifulsoup变量汤。

I'm trying to get values out of soup, but when I do result = soup.findAll("bill") I get an empty list []. How can I extract soup to get dict result of:

我正试图从汤中获取价值,但是当我做结果= soup.findAll(“bill”)时,我得到一个空列表[]。如何提取汤以获得dict结果:

{u'congress': 113,
 u'number': 325,
 u'title': u'A bill to ensure the complete and timely payment of the obligations of the United States Government until May 19, 2013, and for other purposes.',
 u'type': u'hr'}


print type(soup)
print soup 

=> result below

=>结果如下

BeautifulSoup.BeautifulSoup

{
  "bill": {
    "congress": 113, 
    "number": 325, 
    "title": "A bill to ensure the complete and timely payment of the obligations of the United States Government until May 19, 2013, and for other purposes.", 
    "type": "hr"
  }, 
  "category": "passage", 
  "chamber": "s"
}

UPDATE

Here is how I got soup:

这是我如何得到汤:

from BeautifulSoup import BeautifulSoup

import urllib2 
url = urllib2.urlopen("https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json")
content = url.read()
soup = BeautifulSoup(content)

2 个解决方案

#1


8  

Not very familiar with BeautifulSoup but if you just need to decode JSON

不太熟悉BeautifulSoup但是如果你只需要解码JSON

import json

newDictionary=json.loads(str(soup))

#2


13  

You could remove BeautifulSoup:

你可以删除BeautifulSoup:

import json
import urllib2

url = "https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json"
data = json.load(urllib2.urlopen(url))

#1


8  

Not very familiar with BeautifulSoup but if you just need to decode JSON

不太熟悉BeautifulSoup但是如果你只需要解码JSON

import json

newDictionary=json.loads(str(soup))

#2


13  

You could remove BeautifulSoup:

你可以删除BeautifulSoup:

import json
import urllib2

url = "https://www.govtrack.us/data/congress/113/votes/2013/s11/data.json"
data = json.load(urllib2.urlopen(url))