如何发出获取请求并从 python 中的对象获取数据?

How to make fetch request and get data from object in python?

有人可以帮助我吗?我正在执行获取请求并尝试使用 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%22,%22urlToImage%22:%22https://www.sports.ru/dynamic_images/news/110/787/029/3/share/bd571e.jpg%22,%22publishedAt%22:%222022-03-26T13:03:00Z%22,%22content":null}]}

出现错误,未返回值。

您需要遵循对象的嵌套:

  1. 先拿到钥匙'articles'
  2. 然后获取列表的第一个元素
  3. 然后拿到钥匙'source'
  4. 终于拿到钥匙'name'.

您可以使用索引在一行中完成所有这些操作。

newsapi URL returns 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']

方法略有不同,但使用您原来的技术作为基础得到的结果相同。你得到一个 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