从BeautifulSoup中的JSON对象解析出特定值

时间:2019-04-06 21:49:06

标签: json python-3.x parsing beautifulsoup

import urllib
from urllib import request
from bs4 import BeautifulSoup

url = 'http://mygene.info/v3/query?q=symbol:CDK2&species:human&fields=name,symbol,entrezgene'
html = request.urlopen(url).read()
soup = BeautifulSoup(html)

输出:

<html><body><p>{
  "max_score": 88.84169,
  "took": 6,
  "total": 244,
  "hits": [
    {
      "_id": "1017",
      "_score": 88.84169,
      "entrezgene": "1017",
      "name": "cyclin dependent kinase 2",
      "symbol": "CDK2"
    },
    {
      "_id": "12566",
      "_score": 73.8155,
      "entrezgene": "12566",
      "name": "cyclin-dependent kinase 2",
      "symbol": "Cdk2"
    },
    {
      "_id": "362817",
      "_score": 62.09322,
      "entrezgene": "362817",
      "name": "cyclin dependent kinase 2",
      "symbol": "Cdk2"
    }
  ]
}</p></body></html>

目标: 从此输出中,我想解析出entrezgenenamesymbol的值

问题: 我该如何做到这一点?

背景: 我已经尝试过https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-classPython BeautifulSoup extract text between element来命名一对情侣,但找不到我想要的东西

1 个答案:

答案 0 :(得分:3)

您可以获得{em> json 格式的text。然后使用 json.loads() 将其转换为 Dictionary

from urllib import request
from bs4 import BeautifulSoup
import json
url = 'http://mygene.info/v3/query?q=symbol:CDK2&species:human&fields=name,symbol,entrezgene'
html = request.urlopen(url).read()
soup = BeautifulSoup(html,'html.parser')
site_json=json.loads(soup.text)
#printing for entrezgene, do the same for name and symbol
print([d.get('entrezgene') for d in site_json['hits'] if d.get('entrezgene')])

输出:

['1017', '12566', '362817', '100117828', '109992509', '100981695', '100925631']