社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

CodeMonkey

CodeMonkey 最近回复了
4 年前
回复了 CodeMonkey 创建的主题 » 如何在python中发出获取请求并从对象获取数据?

newsapi URL返回带有文章列表的JSON内容,其中每篇文章都有以下结构:

{
    "source": {
        "id": null,
        "name": "Sports.ru"
    },
    "author": "...",
    "title": "... - Sports.ru",
    "description": "...",
    "url": "https://www.sports.ru/basketball/1107870293-lebron-dzhejms-poluchil-zolotuyu-malinu-za-xudshuyu-akterskuyu-rabotu.html",
    "urlToImage": "https://www.sports.ru/dynamic_images/news/110/787/029/3/share/bd571e.jpg",
    "publishedAt": "2022-03-26T13:03:00Z",
    "content": null
}

要从每篇文章中提取特定元素(如描述),请尝试以下方法:

import requests
import json 

response = requests.get('https://newsapi.org/v2/top-headlines?q=sports&country=ru&pageSize=10&apiKey=befce9fd53c04bb695e30568399296c0')
print(response.status_code)

response.encoding = "utf-8"
data = response.json()

# to get the name from source of each article
print([article["source"].get("name") for article in data["articles"]])

# to get the descriptions from each article
# where desc will be a list of descriptions
desc = [article["description"] for article in data["articles"]]
print(desc)

输出:

200
['Sports.ru', 'Sports.ru']
['description1', 'description2']