데이터 분석/데이터 수집

requests

fullfish 2025. 10. 17. 10:32
# 주요함수
requests.get(url, params, headers)
requests.post(url, data,json)
requests.put(url, data)
requests.delete(url)

# requests 객체 속성들
response = requests.get(url)

response.status_code
response.text
response.content
response.json() # JSON 응답을 python객체로 변환
response.headers

# 예제
import requests
url = "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=<>) 해더와 파람스도 넣을 수 있음
import requests
url = "https://api.github.com"
response = requests.get(url)
print("상태 코드:", response.status_code)
print("응답 내용:", response.text[:200])

# post 요청
import requests
url = "https://httpbin.org/post"
data = {"name": "홍길동", "age": 30}
response = requests.post(url, data=data)
print(response.status_code)
print(response.json())

# 이미지 다운로드
import requests
url = "https://www.python.org/static/img/python-logo.png"
response = requests.get(url)
if response.status_code == 200:
    with open("python_logo.png", "wb") as f:  
        f.write(response.content)
    print("이미지 저장 완료")
# w는 write (기존 파일 있으면 덮어쓰고 없으면 만든다)
# b는 binary 텍스트가 아닌 이미지, 동영상, 실행파일. 안쓰면 기본 t로서 텍스트임

'데이터 분석 > 데이터 수집' 카테고리의 다른 글

promise와 coroutine 비교  (0) 2025.10.22
playwright, aiomysql  (0) 2025.10.21
mysql (mysql-connector-python)  (0) 2025.10.21
BeautifulSoup  (0) 2025.10.15
sql 문제 풀이  (0) 2025.10.14