파이썬 요청에서 쿠키를 사용하려면 어떻게 해야 합니까?
페이지에 로그인하여 페이지의 다른 링크에 액세스하려고 합니다.
이 시도에서 "405 Not Allowed" 오류가 발생합니다.
payload={'username'=<username>,'password'=<password>}
with session() as s:
r = c.post(<URL>, data=payload)
print(r)
print(r.content)
Chrome developer tools를 이용하여 post method 세부사항을 확인해보니 API 끝점으로 보이는 URL이 있었습니다.저는 그 URL에 페이로드를 게시했고 작동하는 것처럼 보였습니다. 저는 개발자에게서 볼 수 있는 것과 유사한 반응을 받았습니다.
유감스럽게도 로그인 후 다른 URL을 '얻으려고' 할 때 로그인 페이지에서 내용을 계속 얻고 있습니다.로그인이 고정되지 않는 이유는 무엇입니까?쿠키를 사용할까요? 어떻게?
세션 개체를 사용할 수 있습니다.그것은 당신이 요청을 할 수 있도록 쿠키를 저장하고, 그것은 당신을 위해 쿠키를 처리합니다.
s = requests.Session()
# all cookies received will be stored in the session object
s.post('http://www...',data=payload)
s.get('http://www...')
문서: https://requests.readthedocs.io/en/master/user/advanced/ #http://-
또한 쿠키 데이터를 외부 파일에 저장한 다음 스크립트를 실행할 때마다 로그인하지 않고 세션을 지속적으로 유지하도록 다시 로드할 수 있습니다.
요청(파이썬) 쿠키를 파일에 저장하는 방법은 무엇입니까?
설명서에서 다음을 참조하십시오.
응답에서 쿠키 가져오기
url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) r.cookies
{'example_cookie_name': 'example_cookie_value'}
이후 요청 시 쿠키를 서버에 반환합니다.
url = 'http://httpbin.org/cookies' cookies = {'cookies_are': 'working'} r = requests.get(url, cookies=cookies)`
요약(@Freek Wiekmeijer, @gtalarico) 다른 사람의 대답:
로그인 논리
- 많은 리소스(페이지, api)가 필요함
authentication
그러면 액세스할 수 있습니다. 그렇지 않으면405 Not Allowed
- 흔한
authentication
=grant access
방법:cookie
auth header
Basic xxx
Authorization xxx
사용방법cookie
에requests
작자로서는
- 처음 쿠키 가져오기/생성
- 다음 요청을 위해 쿠키 전송
- 수동 세트
cookie
에headers
- 자동 처리
cookie
타고requests
의session
쿠키 자동 관리response.cookies
쿠키를 수동으로 설정하기
사용하다requests
의session
쿠키 자동 관리
curSession = requests.Session()
# all cookies received will be stored in the session object
payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth
# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)
curSession.get(thirdUrl)
수동으로 제어requests
의response.cookies
payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)
# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)
resp3 = requests.get(thirdUrl, cookies= resp2.cookies)
다른 사람들이 언급했듯이, 다음은 cookie를 문자열 변수로 헤더 매개 변수에 추가하는 방법의 예입니다.
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ...',
'cookie': '_fbp=fb.1.1654447470850.2143140577; _ga=GA1.2.1...'
}
response = requests.get(url, headers=headers)
언급URL : https://stackoverflow.com/questions/31554771/how-can-i-use-cookies-in-python-requests
'itsource' 카테고리의 다른 글
base_url() 함수가 코드 점화기에서 작동하지 않습니다. (0) | 2023.08.20 |
---|---|
os.path.abspath와 os.path.realpath를 모두 사용하는 이유는 무엇입니까? (0) | 2023.08.20 |
git clone에 ssh 옵션 전달 중 (0) | 2023.08.20 |
디지털 오션에서 헤로쿠로 마이그레이션 (0) | 2023.08.20 |
Ajax 호출을 사용한 PHP Excel 다운로드 (0) | 2023.08.20 |