본문 바로가기
Python Requests 기초 강의

Python requests 기초 강의 proxy, user-agent 바꾸는 법 [1강/소스코드 원문]

by 파이썬코딩대학 2024. 12. 30.

 

 

1강 소스코드 자료입니다.

 

import requests

# 1. Requests Get 요청
response = requests.get("https://httpbin.org/get")
print(response.text)
print(response.json())

print(type(response.text), type(response.json()))
print(response.json()['url'], response.json()['origin'])


# 2. Requests GET 요청에서 Parameter, Query String
# name=hello&data=world
params = {"name":"hello","data":"world"}
response = requests.get("https://httpbin.org/get", params=params)
print(response.json()['url'])

# 3. Requests POST 요청
payload = {"name":"hello","data":"world"}
response = requests.post("https://httpbin.org/post",data=payload)

json_data = response.json()
import json

print(json.dumps(json_data,indent=4))

# 4. Requests Header수정 User-Agent 수정
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"}
response = requests.get("https://httpbin.org/user-agent",headers=headers)

useragent = response.text
print(useragent)


# 5. Requests timeout 설정하는 방법
# Requests default timeout 값이 None, Pending
# 나 3초만 기다리겠다
try:
    response = requests.get("https://httpbin.org/delay/5",timeout=3)
    print(response.text)
except Exception as e:
    print("타임아웃 3초 지남", e)

# 6. Requests Proxy 서버 사용하는 방법
proxy_server_url = "27.79.214.215:16000"
proxies = {
    'http':proxy_server_url,
    "https":proxy_server_url
}
response = requests.get("https://httpbin.org/get", proxies=proxies)
json_data = response.json()
import json

print(json.dumps(json_data,indent=4))