使用 Requests 处理网址
学习使用 Python Requests 库发送 GET 和 POST 请求,获取网页内容。
使用 Requests 处理网址 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!
常见问题解答
「使用 Requests 处理网址」课时是免费的吗?
是的 — 「使用 Requests 处理网址」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。
「使用 Requests 处理网址」这节课中我会学到什么?
学习使用 Python Requests 库发送 GET 和 POST 请求,获取网页内容。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Web Scraping & Bots 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「使用 Requests 处理网址」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Web Scraping & Bots 课中编写并运行代码吗?
能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 配置开发环境
- 使用 Requests 处理网址
- 使用 BeautifulSoup 提取数据
- 使用 CSS 选择器遍历 DOM