itsource

Python에서의 HTTP 응답 해석

mycopycode 2023. 3. 28. 21:46
반응형

Python에서의 HTTP 응답 해석

저는 이 URL의 정보를 조작하고 싶습니다.성공적으로 열고 내용을 읽을 수 있습니다.하지만 내가 정말 하고 싶은 것은 내가 원하지 않는 모든 것을 버리고 내가 갖고 싶은 것을 조작하는 것이다.

반복할 수 있도록 문자열을 딕트로 변환할 수 있는 방법이 있나요?아니면 그대로 해석하면 되나요(str type)?

from urllib.request import urlopen

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

print(response.read()) # returns string with info

인쇄했을 때response.read()나는 그것을 알아챘다.b가 문자열에 프리프레인되었습니다(예:b'{"a":1,..) "b"는 바이트를 나타내며 처리 중인 오브젝트의 유형을 선언하는 역할을 합니다.스트링이 dict로 변환될 수 있다는 것을 알았기 때문에json.loads('string')바이트 타입을 문자열 타입으로 변환하기만 하면 됩니다.utf-8에 대한 응답을 디코딩하여 이 작업을 수행했습니다.decode('utf-8')스트링 타입에 들어가자 문제가 해결되어 쉽게 반복할 수 있었습니다.dict.

이것이 가장 빠른 방법인지 가장 '피소닉'한 방법인지는 모르겠지만, 작동하며 최적화와 개선은 항상 늦게 이루어집니다.솔루션 풀코드:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

대신 python의 요청 라이브러리를 사용할 수도 있습니다.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()

이제 파이썬 사전처럼 "dict"를 조작할 수 있습니다.

json는 Python 3의 Unicode 텍스트와 연동하기 때문에(JSON 형식 자체는 Unicode 텍스트로만 정의됩니다), HTTP 응답으로 수신한 바이트를 디코딩해야 합니다.r.headers.get_content_charset('utf-8') 문자 인코딩을 가져옵니다.

#!/usr/bin/env python3
import io
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r, \
     io.TextIOWrapper(r, encoding=r.headers.get_content_charset('utf-8')) as file:
    result = json.load(file)
print(result['headers']['User-Agent'])

사용할 필요가 없습니다.io.TextIOWrapper여기:

#!/usr/bin/env python3
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r:
    result = json.loads(r.read().decode(r.headers.get_content_charset('utf-8')))
print(result['headers']['User-Agent'])

TL&DR: 통상 서버로부터 데이터를 취득하면, 바이트 단위로 송신됩니다.그 이유는, 이러한 바이트를 수신자가 「디코딩」할 필요가 있기 때문에, 수신자는 데이터의 사용법을 알고 있을 필요가 있기 때문입니다.b(바이트)가 아니라 문자열을 얻으려면 도착 시 바이너리를 디코딩해야 합니다.

사용 사례:

import requests    
def get_data_from_url(url):
        response = requests.get(url_to_visit)
        response_data_split_by_line = response.content.decode('utf-8').splitlines()
        return response_data_split_by_line

이 예에서는, 수신한 컨텐츠를 UTF-8 에 디코딩 합니다.그 후, 각 회선을 행 마다 분할해, for 루프를 사용해 루프 할 수 있습니다.

Python 3.4에서는 상황이 달라졌나 봐요.이 방법은 효과가 있었습니다.

print("resp:" + json.dumps(resp.json()))

언급URL : https://stackoverflow.com/questions/23049767/parsing-http-response-in-python

반응형