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']