python - 如何使用请求将某些内容转换为 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 的数据。
解决方案
最好的方法是使用现有的 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 '
# ...}
推荐阅读
- oauth - 如何设置 Airflow DAG 权限以查询基于 Google Sheets 文档构建的 BigQuery 表?
- c - 在 C 中存储和迭代存储的值
- godot - nixos mkDerivation godot 单声道版本(C# 支持)
- python - 如何使用 asyncio/aiohttp 确定最佳缓冲区大小
- apache-httpclient-4.x - 两个互联网上的 HttpClient 连接池
- regex - 不允许正则表达式 大写字母后跟小写字母后跟数字后跟特殊字符
- windows - 通过文件夹共享时程序在哪里运行?
- java - Cassandra Key 可能不是空的错误。字节缓冲区
- java - 如何将 Spinner 用作 ACTION 而不是 SELECTION?
- javascript - 如何在 React 中获取通过 dangerouslySetInnerHTML 添加的子标签的引用