社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Roksana • 3 年前 • 1429 次点击  

谁能帮帮我吗。我正在执行fetch请求,并尝试使用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}]}

获取错误,未返回值。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130057
文章 [ 3 ]  |  最新文章 3 年前
D.L
Reply   •   1 楼
D.L    3 年前

方法稍有不同,但使用原始技术作为基础的结果相同。获取一个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 .

Code-Apprentice
Reply   •   2 楼
Code-Apprentice    3 年前

您需要遵循对象的嵌套:

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

你可以在一行索引中完成这一切。

CodeMonkey
Reply   •   3 楼
CodeMonkey    3 年前

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