URL에 Requests 사용
Python Requests 라이브러리를 사용해 GET 및 POST 요청을 보내 웹 페이지 콘텐츠를 가져오는 방법을 학습합니다.
URL에 Requests 사용은(는) CoddyKit의 무료 Web Scraping & Bots 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Web Scraping & Bots 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Meet Python's Requests Library
Welcome to using Python for web interactions! In this lesson, we'll dive into the Requests library, your go-to tool for making HTTP requests.
Requests simplifies how your Python program talks to websites, acting like a web browser but without a graphical interface. It's essential for fetching web page content before you can extract data.
Setting Up Requests
Before we can use Requests, we need to install it. If you haven't already, open your terminal or command prompt and run the following command:
pip install requests
This command downloads and installs the library, making it available for your Python scripts. It's a one-time setup for your environment.
Your First GET Request
The most common type of request is GET. It's used to retrieve data from a specified resource, much like when your browser loads a webpage.
Let's make a simple GET request to fetch content from example.com. We'll then print the HTTP status code and a snippet of the page's text.
import requests
# Define the URL you want to fetch
url = "http://www.example.com"
# Send a GET request
response = requests.get(url)
# Print the status code and first 200 characters of the content
print(f"Status Code: {response.status_code}")
print(f"Content snippet:\n{response.text[:200]}")Understanding the Response Object
When you make a request, the requests.get() function returns a Response object. This object holds all the information about the server's reply.
response.status_code: An integer indicating the HTTP status (e.g., 200 for OK, 404 for Not Found).response.text: The content of the response, usually HTML, as a string.response.url: The actual URL of the response.
Basic Error Checking
It's good practice to check if your request was successful. The response.raise_for_status() method is a simple way to do this.
If the HTTP status code indicates an error (e.g., 4xx or 5xx), this method will raise an HTTPError. Otherwise, it does nothing.
import requests
url = "http://www.example.com/nonexistent-page"
try:
response = requests.get(url)
response.raise_for_status() # Raises an HTTPError for bad responses (4xx or 5xx)
print("Request successful!")
except requests.exceptions.HTTPError as err:
print(f"HTTP Error occurred: {err}")
except requests.exceptions.ConnectionError as err:
print(f"Connection Error occurred: {err}")
except Exception as err:
print(f"An unexpected error occurred: {err}")Adding Request Headers
Sometimes, websites check for specific HTTP headers to determine if a request is coming from a legitimate browser or a bot.
You can customize your request by passing a dictionary of headers. A common header to set is User-Agent to mimic a browser.
import requests
url = "http://httpbin.org/get" # A service that echoes your request
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Accept-Language": "en-US,en;q=0.9"
}
response = requests.get(url, headers=headers)
print("Your request headers sent to httpbin.org:")
# httpbin.org returns JSON, so we can use .json()
print(response.json()['headers']['User-Agent'])
print(response.json()['headers']['Accept-Language'])Understanding POST Requests
While GET requests are for retrieving data, POST requests are used to send data to a server, typically for creating or updating a resource.
Think of submitting a form on a website – you're usually sending data via a POST request. The data is included in the request body, not in the URL.
Sending Data with POST
To send a POST request with data, you use requests.post() and pass your data as a dictionary to the data parameter.
Let's try sending some simple form data to httpbin.org/post, which will echo back the data it received.
import requests
url = "http://httpbin.org/post"
# Data to send in the POST request
payload = {
"name": "Coddy",
"city": "Kitland",
"age": "5"
}
response = requests.post(url, data=payload)
print("Data received by httpbin.org:")
# The 'form' key in the JSON response contains the sent data
print(response.json()['form'])GET vs. POST: Key Differences
It's crucial to understand when to use GET versus POST:
- GET: Retrieves data, parameters are visible in the URL, requests can be bookmarked and cached. Best for non-sensitive data retrieval.
- POST: Sends data to be processed, parameters are in the request body (not visible in URL), requests are not cached or bookmarked. Best for submitting forms, uploading files, or sensitive data.
Check Your Understanding
You've learned about GET and POST requests. Consider the following scenario:
You want to retrieve the current weather forecast for a specific city from a public API. Which HTTP request method is most appropriate?
Lesson Summary
Great job! You've taken a significant step in understanding how to interact with the web using Python's Requests library.
- We installed the
requestslibrary. - We learned to send GET requests to fetch web content.
- We explored the response object, checking status codes and content.
- We briefly touched on handling request errors.
- We customized requests with headers.
- We learned to send data using POST requests.
- Finally, we distinguished between GET and POST for different web interactions.
Next, we'll learn how to parse the HTML content you've fetched!
AI 튜터와 함께 Python을(를) 배우세요 — 무료
브라우저에서 실제 코드를 작성하고 실행하며, 24/7 AI 튜터로부터 즉각적인 도움을 받고, 웹이나 앱에서 중단한 부분부터 계속 학습하세요.
- 코스
- 12
- 레슨
- 48
자주 묻는 질문
“URL에 Requests 사용” 강의는 무료인가요?
네 — “URL에 Requests 사용” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Web Scraping & Bots 강의 전체를 잠금 해제할 수 있습니다. Web Scraping & Bots 강의에는 총 4개의 강의가 포함되어 있습니다.
“URL에 Requests 사용”에서 뭘 배우나요?
Python Requests 라이브러리를 사용해 GET 및 POST 요청을 보내 웹 페이지 콘텐츠를 가져오는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Web Scraping & Bots을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Web Scraping & Bots을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Web Scraping & Bots은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“URL에 Requests 사용” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Web Scraping & Bots 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Web Scraping & Bots 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 환경 설정
- URL에 Requests 사용
- BeautifulSoup으로 데이터 추출
- CSS 선택자로 DOM 탐색하기