长话短说,我想知道是否可以编码或显示 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 的数据。
最好的方法是使用现有的 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 '
# ...}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句