programing

Python 요청 라이브러리의 get 메서드와 함께 헤더 사용

minecode 2023. 2. 3. 20:57
반응형

Python 요청 라이브러리의 get 메서드와 함께 헤더 사용

최근 우연히 Python에서 HTTP 요청을 처리하는 데 유용한 라이브러리를 발견했습니다. http://docs.python-requests.org/en/latest/index.html에서 찾을 수 있는 곳은 http://docs.python-requests.org/en/latest/index.html입니다.

작업하는 것은 좋지만, get 요청에 헤더를 추가하는 방법을 알 수 없습니다.헬프?

API에 따르면 헤더는 모두 다음과 같이 전달될 수 있습니다.requests.get():

import requests
r=requests.get("http://www.example.com/", headers={"Content-Type":"text"})

당신이 링크한 페이지에 있는 문서들에 따르면 꽤 간단해 보이네요.

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

GET 요구를 송신합니다.돌아온다Response물건.

파라미터:

  • url : 새로운 URLRequest물건.
  • params : (임의) GET 파라미터 딕셔너리Request.
  • headers : (임의) 와 함께 송신하다HTTP 헤더의 딕셔너리Request.
  • cookies : (임의) CookieJar 오브젝트.Request.
  • auth : (옵션)기본 HTTP 인증을 이노블로 하는 Auth Object.
  • timeout : (임의) 요청의 타임아웃을 나타내는 플로트.

답변에서는 세션 전체에 대해 헤더를 설정할 수 있다는 것을 배웠습니다.

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

보너스: 세션에서 쿠키도 처리합니다.

  1. http://myhttpheader.com 에 접속합니다.

  2. 복사 속성 - 일반적으로 'Accept-Language' 및 'User-Agent'입니다.

  3. 사전에 정리합니다.

    headers = { 'Accept-Language' : content-copied-from-myhttpheader,
                'User-Agent':content-copied-from-myhttpheader}
    
  4. 요청의 머리글

    requests.get(url=your_url,headers=headers)
    

언급URL : https://stackoverflow.com/questions/6260457/using-headers-with-the-python-requests-librarys-get-method

반응형