# 주요함수
requests.get(url,params,headers)requests.post(url,data,json)requests.put(url,data)requests.delete(url)# requests 객체 속성들
response=requests.get(url)response.status_coderesponse.textresponse.contentresponse.json()# JSON 응답을 python객체로 변환
response.headers# 예제
importrequestsurl="https://httpbin.org/json"response=requests.get(url)data=response.json()print(type(data))# <class 'dict'>
print(data["slideshow"]["title"])response.json():응답을Python객체로변환json.dump()/json.dumps():Python객체를JSON문자열또는파일로저장json.dumps(obj):Python객체→JSON문자열반환json.dump(obj,f):Python객체→파일(JSON저장)json.loads(str):JSON문자열→Python객체json.load(f):JSON파일→Python객체# get 요청 requests.get(url, headers=<>, params=<>) 해더와 파람스도 넣을 수 있음
importrequestsurl="https://api.github.com"response=requests.get(url)print("상태 코드:",response.status_code)print("응답 내용:",response.text[:200])# post 요청
importrequestsurl="https://httpbin.org/post"data={"name":"홍길동","age":30}response=requests.post(url,data=data)print(response.status_code)print(response.json())# 이미지 다운로드
importrequestsurl="https://www.python.org/static/img/python-logo.png"response=requests.get(url)ifresponse.status_code==200:withopen("python_logo.png","wb")asf:f.write(response.content)print("이미지 저장 완료")# w는 write (기존 파일 있으면 덮어쓰고 없으면 만든다)
# b는 binary 텍스트가 아닌 이미지, 동영상, 실행파일. 안쓰면 기본 t로서 텍스트임