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

时间:2013-11-11 20:11:02

标签: python web-scraping beautifulsoup

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

我使用BeautifulSoup提取JSON并获得beautifulsoup.beautifulsoup变量soup

我正在尝试从soup中获取值,但当我result = 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 

=>结果

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"
}

更新

以下是我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 个答案:

答案 0 :(得分:15)

您可以删除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 :(得分:14)

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

import json

newDictionary=json.loads(str(soup))