[python] 파이썬에서 HTTP GET에 가장 빠른 방법은 무엇입니까?

내용이 문자열이라는 것을 알고 있다면 파이썬에서 HTTP GET에 가장 빠른 방법은 무엇입니까? 다음과 같은 빠른 원 라이너에 대한 설명서를 검색하고 있습니다.

contents = url.get("http://example.com/foo/bar")

그러나 모든 나는 구글이 사용 찾을 수 httpliburllib나는 이러한 라이브러리에서 바로 가기를 찾을 수 없습니다입니다 -.

표준 Python 2.5에는 위와 같은 형식의 단축키가 url_get있습니까? 아니면 함수를 작성해야 합니까?

  1. 쉘 출력을 wget또는 로 캡처하지 않는 것이 curl좋습니다.


답변

파이썬 3 :

import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()

파이썬 2 :

import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()

urllib.request및에 대한 설명서 read.


답변

requests 라는 라이브러리를 사용할 수 있습니다 .

import requests
r = requests.get("http://example.com/foo/bar")

이것은 매우 쉽습니다. 그런 다음 이렇게 할 수 있습니다 :

>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)


답변

httplib2가있는 솔루션을 oneliner로 만들고 싶다면 익명의 Http 객체 인스턴스화를 고려하십시오.

import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")


답변

한 번 봐 가지고 httplib2를 정확하게 당신이 원하는 것을 제공한다 – 매우 유용한 기능이 많이 옆에 -하는.

import httplib2

resp, content = httplib2.Http().request("http://example.com/foo/bar")

내용이 문자열로 응답 본문이되고 resp에는 상태 및 응답 헤더가 포함됩니다.

표준 python 설치에는 포함되어 있지 않지만 표준 python 만 필요하지만 체크 아웃 할 가치가 있습니다.


답변

강력한 urllib3라이브러리로 간단 합니다.

다음과 같이 가져 오십시오.

import urllib3

http = urllib3.PoolManager()

다음과 같이 요청하십시오.

response = http.request('GET', 'https://example.com')

print(response.data) # Raw data.
print(response.data.decode('utf-8')) # Text.
print(response.status) # Status code.
print(response.headers['Content-Type']) # Content type.

헤더도 추가 할 수 있습니다.

response = http.request('GET', 'https://example.com', headers={
    'key1': 'value1',
    'key2': 'value2'
})

자세한 내용은 urllib3 설명서를 참조하십시오 .

urllib3내장 urllib.request또는 http모듈 보다 훨씬 안전하고 사용하기 쉬우 며 안정적입니다.


답변

wget에 대한 theller의 솔루션은 실제로 유용하지만 다운로드 프로세스 전체에서 진행 상황을 인쇄하지는 않습니다. reporthook의 print 문 다음에 한 줄을 추가하면 완벽합니다.

import sys, urllib

def reporthook(a, b, c):
    print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
    sys.stdout.flush()
for url in sys.argv[1:]:
    i = url.rfind("/")
    file = url[i+1:]
    print url, "->", file
    urllib.urlretrieve(url, file, reporthook)
print


답변

다음은 Python의 wget 스크립트입니다.

# From python cookbook, 2nd edition, page 487
import sys, urllib

def reporthook(a, b, c):
    print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
for url in sys.argv[1:]:
    i = url.rfind("/")
    file = url[i+1:]
    print url, "->", file
    urllib.urlretrieve(url, file, reporthook)
print