首页 > 解决方案 > 如何使用请求将某些内容转换为 json

问题描述

长话短说,我想知道是否可以编码或显示 GET 请求的输出以在 json 中以结构化方式显示。例如,如果我这样做:

wiki = requests.get('http://en.wikipedia.org/wiki/Star_Wars', headers={'Content-Type' : 'application/json'})

编码是“text/html; charset=UTF-8”,并且在使用 print(wiki.text) 时显示为一大块文本。我知道 requests 库中有一个 json 方法,但这仅适用于已输出为 json 并将转换为 Python dict 的数据。

标签: pythonpython-3.xpython-requests

解决方案


最好的方法是使用现有的 Wiki API。它适用于其他网站。

如果目标站点没有 API,您可以使用不同的 html 解析器。例如,Beautiful Soup。在该解析过程中,您会获取 json 格式的数据。

from bs4 import BeautifulSoup
from pprint import pprint
import requests

response = requests.get('https://en.wikipedia.org/wiki/Star_Wars')
soup = BeautifulSoup(response.text, 'html.parser')
header = soup.find('h1', class_='firstHeading').text
summary = soup.find('p', class_='').text

pprint({
    'header': header,
    'summary': summary
})

# {'header': 'Star Wars',
#  'summary': 'Star Wars is an American epic space-opera media franchise created '
#             ...}

推荐阅读