有人能幫助我嗎。我正在執行獲取請求并嘗試使用 python 獲取資料。但我收到一個錯誤。
import requests
import json
response_API = requests.get('https://newsapi.org/v2/top-headlines?q=sports&country=ru&pageSize=10&apiKey=befce9fd53c04bb695e30568399296c0')
print(response_API.status_code)
data=response_API.text
parse_json=json.loads(response_API)
active_case=parse_json['name']
print('Total results',active_case)
我正在嘗試name從以下陣列中獲取:
{"status":"ok","totalResults":2,"articles":[{"source":{"id":null,"**name**":"Sports.ru"},"author":"Валерий Левкин","title":"Леброн Джеймс получил ?Золотую малину? за худшую актерскую работу - Sports.ru","description":"В США названы обладатели антинаграды ?Золотая малина? по итогам 2021 года.","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}]}
出錯,不回傳值。
uj5u.com熱心網友回復:
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']
uj5u.com熱心網友回復:
您需要遵循物件的嵌套:
- 先拿到鑰匙
'articles' - 然后獲取串列的第一個元素
- 然后拿到鑰匙
'source' - 終于拿到鑰匙了
'name'。
您可以使用索引在一行中完成所有操作。
uj5u.com熱心網友回復:
方法略有不同,但以您的原始技術為基礎,結果相同。您得到一個 json 字串,然后將其轉換為 json,然后搜索您想要的位。
import requests
import json
response_API = requests.get('https://newsapi.org/v2/top-headlines?q=sports&country=ru&pageSize=10&apiKey=befce9fd53c04bb695e30568399296c0')
print(response_API.status_code)
# this is a json string
data=response_API.text
# convert string to json
parse_json=json.loads(data)
print('here is the json....')
print(parse_json)
# get an element form json
active_case=parse_json['articles'][0]
# print the result
print('here is the active case...')
print(active_case)
這是結果,您可以從中提取您喜歡的內容:
{'source': {'id': None, 'name': 'Sports.ru'}, 'author': 'Валерий Левкин', 'title': 'Леброн Джеймс получил ?Золотую малину? за худшую актерскую работу - Sports.ru', 'description': 'В США названы обладатели антинаграды ?Золотая малина? по итогам 2021 года.', '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': None}, {'source': {'id': None, 'name': 'Sports.ru'}, 'author': 'Андрей Карнаухов', 'title': 'Овечкин забил 771-й гол в НХЛ. До Хоу – 30 шайб - Sports.ru', 'description': 'Капитан\xa0?Вашингтона?\xa0Александр Овечкин\xa0забросил\xa0шайбу, а также забил победный буллит в серии в матче с ?Баффало? (4:3 Б) и был признан третьей звездой.', 'url': 'https://www.sports.ru/hockey/1107860736-ovechkin-zabil-771-j-gol-v-nxl-do-xou-30-shajb.html', 'urlToImage': 'https://www.sports.ru/dynamic_images/news/110/786/073/6/share/c9cb18.jpg', 'publishedAt': '2022-03-26T01:56:15Z', 'content': None}
這里的結果很簡單dict。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/449937.html
