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>
目标:
从此输出中,我想解析出entrezgene
,name
和symbol
的值
问题: 我该如何做到这一点?
背景: 我已经尝试过https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class和Python BeautifulSoup extract text between element来命名一对情侣,但找不到我想要的东西
答案 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']