0Pricing
Web Scraping & Bots · 课时

处理用户身份验证

构建能够使用凭据登录网站,并处理会话管理和 Cookie 的机器人。

处理用户身份验证 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Web Scraping & Bots 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Web Scraping & Bots 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Bots Need to Log In

Many websites require you to log in to access certain data or features. Bots often need to simulate this process to get past paywalls, access dashboards, or retrieve personalized content.

  • Access restricted content.
  • Perform user-specific actions.
  • Maintain a persistent identity.

Understanding Login Forms

When you log in manually, your browser sends your username and password to the server. This is usually done via an HTTP POST request to a specific URL.

  • POST request: Sends data securely in the request body.
  • Form fields: Input fields for credentials (e.g., username, password).
  • Action URL: The server endpoint that processes the login.

Finding Login Form Details

To automate a login, you need to identify the form's action URL and the name attributes of the input fields (username, password). Browser developer tools are essential here.

  • Right-click on the login form → "Inspect".
  • Look for the <form> tag: find its action attribute.
  • Look for <input> tags: find their name attributes for credentials.

Sending Login Data with Requests

The Python requests library can send POST requests. You'll prepare a dictionary of your credentials and pass it to requests.post().

  • The dictionary keys should match the input field name attributes.
  • The values will be your username and password.
  • The url will be the form's action URL.

Basic Login Attempt

Here's a simple example of trying to log in. Note that without session management, you'll likely be logged out immediately after the request, as no cookies are persisted.

import requests

login_url = "http://httpbin.org/post" # Example URL
credentials = {
    "username": "my_user",
    "password": "my_password"
}

response = requests.post(login_url, data=credentials)

print(f"Status Code: {response.status_code}")
print("Response data (simulated):")
print(response.json().get('form'))

Sessions & Cookies for Persistence

After a successful login, websites typically send back a cookie. This small piece of data is stored by your browser and sent with subsequent requests, telling the server you're still logged in.

  • Session: A continuous interaction between a user and a website.
  • Cookies: Small text files used by websites to remember information about you.
  • Crucial for maintaining a logged-in state across multiple page visits.

Managing Sessions with `requests.Session()`

The requests library has a Session object that automatically handles cookies for you. Once you log in using a Session object, it will include the authentication cookies in all subsequent requests made through that same session.

  • Create a session object: s = requests.Session().
  • Use s.post() for login and s.get() for subsequent requests.
  • No need to manually manage cookies.

Login with `requests.Session()`

This example demonstrates how to use requests.Session() to maintain your logged-in state. After logging in, the session object automatically includes the cookies for the subsequent GET request.

import requests

login_url = "http://httpbin.org/post" # Example login endpoint
dashboard_url = "http://httpbin.org/get" # Example page after login

credentials = {
    "username": "my_user",
    "password": "my_password"
}

with requests.Session() as s:
    # First, post login data
    login_response = s.post(login_url, data=credentials)
    print(f"Login Status: {login_response.status_code}")
    print(f"Cookies after login: {s.cookies.get_dict()}")

    # Now, access a protected page using the same session
    protected_page_response = s.get(dashboard_url)
    print(f"Protected Page Status: {protected_page_response.status_code}")
    print("Protected page content snippet:")
    print(protected_page_response.text[:100])

Checking Login Success

How do you know if your bot actually logged in successfully? It's crucial to verify the outcome.

  • Status Code: A 200 OK often means success, but sometimes redirects happen (e.g., 302 Found).
  • Redirects: Check response.history to see if you were redirected to a dashboard or profile page.
  • Page Content: Look for specific text that only appears when logged in (e.g., "Welcome, [username]", a "Logout" button, or absence of login form).

Session Management Check

You're building a bot to log into a website and then navigate to a profile page. Which of the following are true about using requests.Session()?

Recap: User Authentication

In this lesson, we learned how to build bots that can log into websites to access protected content.

  • We covered inspecting login forms to find the action URL and input field names.
  • We used requests.post() to send credentials.
  • Most importantly, we learned to use requests.Session() to manage and persist cookies, allowing our bots to stay logged in and access authenticated content.
  • Finally, we discussed how to verify successful logins by checking status codes, redirects, and page content.

常见问题解答

「处理用户身份验证」课时是免费的吗?

是的 — 「处理用户身份验证」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。

「处理用户身份验证」这节课中我会学到什么?

构建能够使用凭据登录网站,并处理会话管理和 Cookie 的机器人。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web Scraping & Bots 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「处理用户身份验证」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web Scraping & Bots 课中编写并运行代码吗?

能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 处理用户身份验证
  2. 模拟复杂用户流程
  3. 与 API 集成
  4. 管理会话与 Cookie
← 返回 Web Scraping & Bots