Python lấy json từ các yêu cầu url

Trong hướng dẫn này, bạn sẽ học cách phân tích phản hồi yêu cầu Python dưới dạng JSON và chuyển đổi nó thành từ điển Python. Bất cứ khi nào thư viện requests được sử dụng để đưa ra yêu cầu, một đối tượng Response được trả về. Thư viện Python requests cung cấp một phương thức hữu ích, json(), để chuyển đổi một đối tượng Response thành một từ điển Python

Đến cuối hướng dẫn này, bạn sẽ học được

  • Cách phân tích cú pháp requests.Response sang từ điển Python bằng phương thức
    # Accessing Data in a Python Request Response
    import requests
    resp = requests.get('https://reqres.in/api/users')
    resp_dict = resp.json()
    
    print(resp_dict.get('page'))
    
    # Returns: 1
    0
  • Cách chuyển đổi phản hồi JSON yêu cầu Python thành từ điển
  • Cách xử lý lỗi khi phân tích cú pháp phản hồi JSON yêu cầu Python
  • Cách chuyển đổi đối tượng JSON yêu cầu Python thành Pandas DataFrame

Mục lục

Phân tích cú pháp các yêu cầu Python Phản hồi Nội dung JSON

Mọi yêu cầu được thực hiện bằng thư viện Python requests đều trả về một đối tượng Response. Điều này đúng với bất kỳ loại yêu cầu nào được đưa ra, bao gồm yêu cầu

# Accessing Data in a Python Request Response
import requests
resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()

print(resp_dict.get('page'))

# Returns: 1
3,
# Accessing Data in a Python Request Response
import requests
resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()

print(resp_dict.get('page'))

# Returns: 1
4 và
# Accessing Data in a Python Request Response
import requests
resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()

print(resp_dict.get('page'))

# Returns: 1
5. Thư viện requests cung cấp một số cách khác nhau để truy cập nội dung của đối tượng phản hồi

  • # Accessing Data in a Python Request Response
    import requests
    resp = requests.get('https://reqres.in/api/users')
    resp_dict = resp.json()
    
    print(resp_dict.get('page'))
    
    # Returns: 1
    7 trả về nội dung thực theo byte
  • # Accessing Data in a Python Request Response
    import requests
    resp = requests.get('https://reqres.in/api/users')
    resp_dict = resp.json()
    
    print(resp_dict.get('page'))
    
    # Returns: 1
    8 trả về nội dung được chuyển đổi thành chuỗi, sử dụng mã hóa ký tự, chẳng hạn như UTF-8

Vì bạn đang đọc một bài viết về cách phân tích cú pháp JSON từ phản hồi thành từ điển Python, nên hai tùy chọn trên có thể không lý tưởng. Mặc dù bạn có thể sử dụng thư viện

# Accessing Data in a Python Request Response
import requests
resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()

print(resp_dict.get('page'))

# Returns: 1
9 để tuần tự hóa phản hồi, nhưng điều này sẽ thêm một bước bổ sung và độ phức tạp cho mã của bạn

Thư viện requests đi kèm với một phương pháp hữu ích,

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
1, giúp tuần tự hóa phản hồi của yêu cầu. Để xem một ví dụ, hãy để các điểm cuối công khai được cung cấp bởi trang web
# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
2. Các điểm cuối này hoạt động mà không cần đăng ký, vì vậy thật dễ dàng để làm theo hướng dẫn

Hãy xem cách chúng ta có thể truy cập điểm cuối

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
3 và tuần tự hóa phản hồi vào từ điển Python bằng phương pháp
# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
1

# Serializing a GET Request with .json()
import requests
resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()

print(type(resp_dict))

# Returns: <class 'dict'>

Từ đoạn mã trên, chúng ta có thể thấy rằng việc áp dụng phương thức

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
1 cho phản hồi của chúng ta đã tạo ra một từ điển Python. Trong phần sau, bạn sẽ học cách làm việc với từ điển kết quả để truy cập một số nội dung

Cách truy cập Python yêu cầu Nội dung phản hồi dưới dạng từ điển

Sau khi áp dụng phương pháp

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
1 cho phản hồi được tạo bởi thư viện requests, chúng tôi đã tạo một từ điển. Điều này có nghĩa là chúng ta có thể truy cập dữ liệu trong từ điển bằng cách sử dụng các phương pháp từ điển phổ biến, chẳng hạn như lập chỉ mục ngoặc vuông hoặc phương pháp
# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
8

Hãy xem cách chúng ta có thể truy cập khóa

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
9 trong dữ liệu

# Accessing Data in a Python Request Response
import requests
resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()

print(resp_dict.get('page'))

# Returns: 1

Trong đoạn mã trên, chúng tôi đã áp dụng phương pháp

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
8 để truy cập giá trị tương ứng với khóa
# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
9. Sử dụng phương pháp
# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
8 là cách an toàn hơn để xử lý thao tác này. Điều này là do phương thức sẽ chỉ trả về
import json
import requests

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
pretty = json.dumps(resp_dict, indent=4)
print(pretty)

# Returns: 
# {
#     "page": 1,
#     "per_page": 6,
#     "total": 12,
#     "total_pages": 2,
#     "data": [
#         {
#             "id": 1,
#             "email": "[email protected]",
#             "first_name": "George",
#             "last_name": "Bluth",
#             "avatar": "https://reqres.in/img/faces/1-image.jpg"
#         },
#         ...
#         {
#             "id": 6,
#             "email": "[email protected]",
#             "first_name": "Tracey",
#             "last_name": "Ramos",
#             "avatar": "https://reqres.in/img/faces/6-image.jpg"
#         }
#     ],
#     "support": {
#         "url": "https://reqres.in/#support-heading",
#         "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
#     }
# }
3, nếu khóa không tồn tại

Cách xử lý lỗi khi phân tích cú pháp phản hồi JSON từ các yêu cầu Python

Trong một số trường hợp, dữ liệu được trả về từ một đối tượng Response không thể được đánh số thứ tự. Trong những trường hợp này, bạn sẽ gặp phải một

import json
import requests

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
pretty = json.dumps(resp_dict, indent=4)
print(pretty)

# Returns: 
# {
#     "page": 1,
#     "per_page": 6,
#     "total": 12,
#     "total_pages": 2,
#     "data": [
#         {
#             "id": 1,
#             "email": "[email protected]",
#             "first_name": "George",
#             "last_name": "Bluth",
#             "avatar": "https://reqres.in/img/faces/1-image.jpg"
#         },
#         ...
#         {
#             "id": 6,
#             "email": "[email protected]",
#             "first_name": "Tracey",
#             "last_name": "Ramos",
#             "avatar": "https://reqres.in/img/faces/6-image.jpg"
#         }
#     ],
#     "support": {
#         "url": "https://reqres.in/#support-heading",
#         "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
#     }
# }
5. Bạn có thể xử lý các lỗi này một cách an toàn bằng cách gói yêu cầu của mình trong một khối
import json
import requests

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
pretty = json.dumps(resp_dict, indent=4)
print(pretty)

# Returns: 
# {
#     "page": 1,
#     "per_page": 6,
#     "total": 12,
#     "total_pages": 2,
#     "data": [
#         {
#             "id": 1,
#             "email": "[email protected]",
#             "first_name": "George",
#             "last_name": "Bluth",
#             "avatar": "https://reqres.in/img/faces/1-image.jpg"
#         },
#         ...
#         {
#             "id": 6,
#             "email": "[email protected]",
#             "first_name": "Tracey",
#             "last_name": "Ramos",
#             "avatar": "https://reqres.in/img/faces/6-image.jpg"
#         }
#     ],
#     "support": {
#         "url": "https://reqres.in/#support-heading",
#         "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
#     }
# }
6

Hãy xem cách chúng ta có thể xử lý một cách an toàn một

import json
import requests

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
pretty = json.dumps(resp_dict, indent=4)
print(pretty)

# Returns: 
# {
#     "page": 1,
#     "per_page": 6,
#     "total": 12,
#     "total_pages": 2,
#     "data": [
#         {
#             "id": 1,
#             "email": "[email protected]",
#             "first_name": "George",
#             "last_name": "Bluth",
#             "avatar": "https://reqres.in/img/faces/1-image.jpg"
#         },
#         ...
#         {
#             "id": 6,
#             "email": "[email protected]",
#             "first_name": "Tracey",
#             "last_name": "Ramos",
#             "avatar": "https://reqres.in/img/faces/6-image.jpg"
#         }
#     ],
#     "support": {
#         "url": "https://reqres.in/#support-heading",
#         "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
#     }
# }
5 bằng cách sử dụng thư viện requests

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')

Cách in đẹp một đối tượng JSON từ các yêu cầu Python

Trong phần này, chúng ta sẽ xem cách in đẹp một đối tượng JSON được trả về từ việc sử dụng thư viện Python requests. Việc in một tệp JSON đẹp được thực hiện dễ dàng bằng cách sử dụng hàm

# Converting JSON Data to a Pandas DataFrame
import requests
import pandas as pd

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
df = pd.DataFrame(resp_dict.get('data'))
print(df)

# Returns: 
#    id                     email first_name last_name                                   avatar
# 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
# 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
# 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
# 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
# 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
# 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg
0

Hãy xem cách chúng ta có thể in một đối tượng JSON từ thư viện Python requests

import json
import requests

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
pretty = json.dumps(resp_dict, indent=4)
print(pretty)

# Returns: 
# {
#     "page": 1,
#     "per_page": 6,
#     "total": 12,
#     "total_pages": 2,
#     "data": [
#         {
#             "id": 1,
#             "email": "[email protected]",
#             "first_name": "George",
#             "last_name": "Bluth",
#             "avatar": "https://reqres.in/img/faces/1-image.jpg"
#         },
#         ...
#         {
#             "id": 6,
#             "email": "[email protected]",
#             "first_name": "Tracey",
#             "last_name": "Ramos",
#             "avatar": "https://reqres.in/img/faces/6-image.jpg"
#         }
#     ],
#     "support": {
#         "url": "https://reqres.in/#support-heading",
#         "text": "To keep ReqRes free, contributions towards server costs are appreciated!"
#     }
# }

Hãy chia nhỏ những gì chúng ta đã làm trong đoạn mã trên

  1. Chúng tôi đã tải phản hồi của yêu cầu
    # Accessing Data in a Python Request Response
    import requests
    resp = requests.get('https://reqres.in/api/users')
    resp_dict = resp.json()
    
    print(resp_dict.get('page'))
    
    # Returns: 1
    3
  2. Chúng tôi đã tuần tự hóa phản hồi bằng cách sử dụng phương pháp
    # Handling a JSONDecodeError in Python
    from json import JSONDecodeError
    import requests
    resp = requests.get('https://reqres.in/api/users/page4')
    try:
        resp_dict = resp.json()
    except JSONDecodeError:
        print('Response could not be serialized')
    1
  3. Sau đó, chúng tôi đã sử dụng hàm
    # Converting JSON Data to a Pandas DataFrame
    import requests
    import pandas as pd
    
    resp = requests.get('https://reqres.in/api/users')
    resp_dict = resp.json()
    df = pd.DataFrame(resp_dict.get('data'))
    print(df)
    
    # Returns: 
    #    id                     email first_name last_name                                   avatar
    # 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
    # 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
    # 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
    # 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
    # 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
    # 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg
    4 với thụt lề là 4 để in phản hồi

Cách chuyển đổi đối tượng JSON yêu cầu Python thành Pandas DataFrame

Trong phần cuối cùng này, chúng ta sẽ xem cách chuyển đổi đối tượng

# Converting JSON Data to a Pandas DataFrame
import requests
import pandas as pd

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
df = pd.DataFrame(resp_dict.get('data'))
print(df)

# Returns: 
#    id                     email first_name last_name                                   avatar
# 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
# 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
# 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
# 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
# 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
# 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg
5 thành Khung dữ liệu Pandas. Vì Pandas cho phép bạn dễ dàng tạo DataFrames từ danh sách từ điển, nên chúng tôi chỉ cần chuyển một phần phản hồi được tuần tự hóa của mình

Từ đoạn mã trên, chúng tôi biết rằng dữ liệu được lưu trữ trong một khóa có tên

# Converting JSON Data to a Pandas DataFrame
import requests
import pandas as pd

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
df = pd.DataFrame(resp_dict.get('data'))
print(df)

# Returns: 
#    id                     email first_name last_name                                   avatar
# 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
# 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
# 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
# 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
# 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
# 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg
6 dưới dạng danh sách từ điển. Chúng ta có thể dễ dàng chuyển từ điển này vào hàm tạo Pandas DataFrame và chuyển đổi nó thành DataFrame

# Converting JSON Data to a Pandas DataFrame
import requests
import pandas as pd

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
df = pd.DataFrame(resp_dict.get('data'))
print(df)

# Returns: 
#    id                     email first_name last_name                                   avatar
# 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
# 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
# 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
# 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
# 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
# 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg

Trong đoạn mã trên, chúng tôi đã tuần tự hóa phản hồi của mình cho một từ điển. Từ đó, chúng tôi đã chuyển các giá trị của khóa

# Converting JSON Data to a Pandas DataFrame
import requests
import pandas as pd

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
df = pd.DataFrame(resp_dict.get('data'))
print(df)

# Returns: 
#    id                     email first_name last_name                                   avatar
# 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
# 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
# 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
# 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
# 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
# 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg
6 vào hàm tạo
# Converting JSON Data to a Pandas DataFrame
import requests
import pandas as pd

resp = requests.get('https://reqres.in/api/users')
resp_dict = resp.json()
df = pd.DataFrame(resp_dict.get('data'))
print(df)

# Returns: 
#    id                     email first_name last_name                                   avatar
# 0   1    [email protected]     George     Bluth  https://reqres.in/img/faces/1-image.jpg
# 1   2    [email protected]      Janet    Weaver  https://reqres.in/img/faces/2-image.jpg
# 2   3       [email protected]       Emma      Wong  https://reqres.in/img/faces/3-image.jpg
# 3   4        [email protected]        Eve      Holt  https://reqres.in/img/faces/4-image.jpg
# 4   5  [email protected]    Charles    Morris  https://reqres.in/img/faces/5-image.jpg
# 5   6    [email protected]     Tracey     Ramos  https://reqres.in/img/faces/6-image.jpg
8, chấp nhận danh sách từ điển

Phần kết luận

Trong hướng dẫn này, bạn đã học cách sử dụng đối tượng Response của thư viện Python requests và tuần tự hóa dữ liệu JSON bằng phương thức

# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
1. Lần đầu tiên bạn học cách sử dụng phương pháp
# Handling a JSONDecodeError in Python
from json import JSONDecodeError
import requests
resp = requests.get('https://reqres.in/api/users/page4')
try:
    resp_dict = resp.json()
except JSONDecodeError:
    print('Response could not be serialized')
1. Sau đó, bạn đã học cách truy cập dữ liệu từ từ điển kết quả. Bạn cũng đã học cách xử lý các lỗi do phương pháp này gây ra, cách in đẹp dữ liệu kết quả và cách tải dữ liệu đó vào Khung dữ liệu Pandas

Làm cách nào để phân tích cú pháp JSON trong các yêu cầu Python?

Để phân tích chuỗi dữ liệu JSON thành đối tượng Python, hãy sử dụng json. loads() của gói dựng sẵn có tên json . json. phương thức loading() phân tích cú pháp chuỗi dữ liệu JSON được cung cấp và trả về một từ điển Python chứa tất cả dữ liệu từ JSON.

Làm cách nào để lấy JSON từ điểm cuối bằng Python?

Để nhận JSON từ điểm cuối API REST bằng Python, bạn phải gửi yêu cầu HTTP GET đến máy chủ API REST và cung cấp Chấp nhận. tiêu đề yêu cầu ứng dụng/json . chấp nhận. tiêu đề application/json cho máy chủ API REST biết rằng ứng dụng khách API muốn nhận dữ liệu ở định dạng JSON.

Làm cách nào để chuyển đổi nội dung yêu cầu thành JSON trong Python?

Nếu bạn có một đối tượng Python, bạn có thể chuyển đổi nó thành một chuỗi JSON bằng cách sử dụng json. phương thức dumps() .

Làm cách nào để lấy dữ liệu JSON từ bất kỳ trang web nào?

Dưới đây là ba bước chính cho bản trình diễn này. .
Kiểm tra trang web trong trình duyệt - để xác định URL chứa tệp JSON mà chúng tôi cần
Tạo hàng loạt danh sách URL JSON trong Octopude - để trích xuất từ ​​danh sách các liên kết tệp JSON
Chọn dữ liệu để trích xuất - để lấy dữ liệu chúng tôi cần