Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- intent
- 앱
- Flutter
- textfield
- TEST
- 계측
- scroll
- drift
- appbar
- binding
- CustomScrollView
- Coroutines
- DART
- data
- android
- Button
- 안드로이드
- LifeCycle
- textview
- Compose
- 테스트
- Kotlin
- tabbar
- viewmodel
- livedata
- Dialog
- activity
- ScrollView
- 앱바
- Navigation
Archives
- Today
- Total
Study Record
[파이썬(python)] 웹 요청 모듈 - requests 본문
728x90
Requests
→ 공식문서 : https://docs.python-requests.org/en/master/
Requests: HTTP for Humans™ — Requests 2.26.0 documentation
Requests: HTTP for Humans™ Release v2.26.0. (Installation) Requests is an elegant and simple HTTP library for Python, built for human beings. Behold, the power of Requests: >>> r = requests.get('https://api.github.com/user', auth=('user', 'pass')) >>> r.
docs.python-requests.org
1. requests 모듈 추가하기
[pycharm]
① Files → Settings 에서 + 버튼을 누른다.
② requests 을 검색하여 Install Package 를 통해 설치하면 끝난다!
2. requests 모듈 사용하기
get 요청
url = 'https://httpbin.org/get'
# 파라미터는 튜블형식도 허용한다.
params = {'key1': 'value1'}
params = {'key1': 'value1', 'key2': 'value2', 'key3': ['value1', 'value2']}
# 헤더에 user-agent 를 설정하지 않으면 파이썬 혹은 파이참이라고 표시가 나온다.
# 이렇게 그대로 보내면 차단할 가능성이 크므로 잘 알려진 크롬이나 파이어폭스로 바꿔준다.
headers = {'user-agent': 'my-app/0.0.1'}
# 프록시를 지정할 수 있다.
proxies = {'http': 'http://localhost:8080', 'https': 'https://localhost:8080'}
# 요청하기
r = requests.get(url)
r = requests.get(url, params=params)
r = requests.get(url, headers=headers)
r = requests.get(url, proxies=proxies)
# 한꺼번에 지정하기
r = requests.get(url, params=params, headers=headers, proxies=proxies)
# 결과 받아보기
r.status_code # 200
r.text # 내용 출력
r.headers # 헤더 출력
r.headers['Content-Type']
r.cookies
r.history # 리다이렉션 기록
post 요청
url = 'https://api.github.com/events'
data = {'some': 'data'}
data = {'key1': 'value1', 'key2': 'value2', 'key3': ['value1', 'value2']}
headers = {'user-agent': 'my-app/0.0.1'}
proxies = {'http': 'http://localhost:8080', 'https': 'https://localhost:8080'}
# 파일지정
files = {'file': 'file contents'}
files = {'file': open('report.xls', 'rb')}
files = {'file': open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'}}
# 요청하기
r = requtest.post(url, data=data)
r = requests.post(url, json=data)
r = requests.post(url, files=files)
# 한꺼번에 요청하기
r = requests.post(url, headers=headers, data=data, proxies=proxies)
Session 사용하기
url = 'https://api.github.com/events'
data = {'username':'admin', 'password':'password', 'Login':'Login'}
proxies = {'http':'http://localhost:8080', 'https':'http://localhost:8080'}
# 포맷 1
s = reqeusts.Session()
req = request.Request('POST', url, data=data)
prepared = s.prepare_request(req)
resp = s.send(prepared, proxies=proxies)
# 포맷 2
s = requests.Session()
resp = s.post(url, data=data, proxies=proxies)
728x90