亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

目錄
? 1. Required Libraries
? 2. Example: Login and Scrape a Page
? 3. Key Points to Remember
? 4. Real-World Example (Generic Pattern)
? 5. Alternative: Use Selenium for JavaScript-heavy Sites
首頁(yè) 后端開(kāi)發(fā) Python教程 Python Web刮擦與登錄示例

Python Web刮擦與登錄示例

Jul 31, 2025 am 09:24 AM

使用requests.Session()發(fā)送POST請(qǐng)求并維護(hù)會(huì)話以登錄網(wǎng)站;2. 通過(guò)BeautifulSoup解析登錄頁(yè)面獲取隱藏字段如CSRF令牌;3. 構(gòu)造包含用戶名、密碼和令牌的登錄數(shù)據(jù)并提交;4. 驗(yàn)證登錄是否成功,檢查響應(yīng)內(nèi)容中的“Logout”或“Dashboard”等標(biāo)志;5. 登錄成功后用同一會(huì)話訪問(wèn)受保護(hù)頁(yè)面并抓取所需內(nèi)容;6. 對(duì)于JavaScript動(dòng)態(tài)渲染的頁(yè)面應(yīng)改用Selenium模擬瀏覽器操作;7. 始終遵守網(wǎng)站的robots.txt和使用條款,避免生產(chǎn)環(huán)境硬編碼憑證,推薦使用環(huán)境變量存儲(chǔ)敏感信息,最終確保 scraping 行為合法合規(guī)。

python web scraping with login example

If you need to scrape a website that requires login, you’ll typically need to send a POST request with your credentials first, maintain the session, and then access the protected pages. Here's a practical example using Python’s requests and BeautifulSoup libraries to log in and scrape a page behind authentication.

python web scraping with login example

We’ll use a dummy login form structure (like many real sites) and show how to handle it.


? 1. Required Libraries

Install the needed packages if you haven't:

python web scraping with login example
pip install requests beautifulsoup4

? 2. Example: Login and Scrape a Page

import requests
from bs4 import BeautifulSoup

# Step 1: Start a session
session = requests.Session()

# Step 2: URL of the login page (example)
login_url = 'https://httpbin.org/post'  # Placeholder - replace with actual login URL
target_url = 'https://example.com/dashboard'  # Page you want to scrape after login

# Step 3: Get login page (to extract hidden form fields like CSRF tokens if needed)
login_page = session.get('https://example.com/login')
soup = BeautifulSoup(login_page.content, 'html.parser')

# Optional: Extract hidden inputs (e.g., CSRF token)
csrf_token = soup.find('input', {'name': 'csrf_token'})['value']  # Adjust name as needed

# Step 4: Prepare login payload
payload = {
    'username': 'your_username',
    'password': 'your_password',
    'csrf_token': csrf_token  # Include if present
}

# Step 5: Submit login form
response = session.post('https://example.com/login', data=payload)

# Step 6: Check if login was successful
if "Logout" in response.text or "Dashboard" in response.text:
    print("? Login successful")
else:
    print("? Login failed")
    print(response.status_code)
    print(response.text[:500])  # Debug output
    exit()

# Step 7: Scrape a protected page
protected_page = session.get(target_url)
soup = BeautifulSoup(protected_page.content, 'html.parser')

# Example: Extract page title or specific content
print("Page Title:", soup.title.string)
# Or scrape data
data = soup.find_all('div', class_='content')  # Adjust selector
for item in data:
    print(item.get_text(strip=True))

? 3. Key Points to Remember

  • Session Persistence: Use requests.Session() to keep cookies and stay logged in.
  • Inspect the Login Form: Use browser DevTools (F12) to:
    • Find the correct login URL (form’s action attribute)
    • Check input field names (e.g., username, email, password, csrf_token)
  • CSRF & Hidden Fields: Many sites require tokens — always check for hidden inputs.
  • HTTPS & Security: Never hardcode credentials in production. Use environment variables:
    import os
    username = os.getenv('LOGIN_USER')
    password = os.getenv('LOGIN_PASS')
  • Respect robots.txt and Terms of Service — scraping may be prohibited.

? 4. Real-World Example (Generic Pattern)

import requests
from bs4 import BeautifulSoup
import os

session = requests.Session()

# Load credentials
USER = os.getenv('USERNAME', 'test@example.com')
PASS = os.getenv('PASSWORD', 'secret')

# Fetch login page
resp = session.get('https://example.com/login')
soup = BeautifulSoup(resp.text, 'html.parser')

# Extract CSRF token
token = soup.find('input', {'name': 'authenticity_token'})['value']

# Login data
data = {
    'authenticity_token': token,
    'user[email]': USER,
    'user[password]': PASS,
    'commit': 'Log in'
}

# Post to login
r = session.post('https://example.com/sessions', data=data)

# Now scrape
dashboard = session.get('https://example.com/my-account')

? 5. Alternative: Use Selenium for JavaScript-heavy Sites

If the login is handled by JavaScript (e.g., React, Vue), use Selenium:

from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://example.com/login")

driver.find_element(By.NAME, "username").send_keys("your_user")
driver.find_element(By.NAME, "password").send_keys("your_pass")
driver.find_element(By.XPATH, "//button[@type='submit']").click()

# Wait and go to target page
driver.implicitly_wait(5)
driver.get("https://example.com/profile")

print(driver.page_source)
driver.quit()

Basically, for simple forms: requests Session works great. For dynamic sites: go with Selenium. Always test on a small scale and check the site’s policies.

python web scraping with login example

以上是Python Web刮擦與登錄示例的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動(dòng)的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機(jī)

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強(qiáng)大的PHP集成開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

Python類(lèi)中的多態(tài)性 Python類(lèi)中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實(shí)現(xiàn)”,允許統(tǒng)一處理不同類(lèi)型的對(duì)象。1.多態(tài)通過(guò)方法重寫(xiě)實(shí)現(xiàn),子類(lèi)可重新定義父類(lèi)方法,如Animal類(lèi)的speak()方法在Dog和Cat子類(lèi)中有不同實(shí)現(xiàn)。2.多態(tài)的實(shí)際用途包括簡(jiǎn)化代碼結(jié)構(gòu)、增強(qiáng)可擴(kuò)展性,例如圖形繪制程序中統(tǒng)一調(diào)用draw()方法,或游戲開(kāi)發(fā)中處理不同角色的共同行為。3.Python實(shí)現(xiàn)多態(tài)需滿足:父類(lèi)定義方法,子類(lèi)重寫(xiě)該方法,但不要求繼承同一父類(lèi),只要對(duì)象實(shí)現(xiàn)相同方法即可,這稱為“鴨子類(lèi)型”。4.注意事項(xiàng)包括保持方

Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

參數(shù)(parameters)是定義函數(shù)時(shí)的占位符,而傳參(arguments)是調(diào)用時(shí)傳入的具體值。1.位置參數(shù)需按順序傳遞,順序錯(cuò)誤會(huì)導(dǎo)致結(jié)果錯(cuò)誤;2.關(guān)鍵字參數(shù)通過(guò)參數(shù)名指定,可改變順序且提高可讀性;3.默認(rèn)參數(shù)值在定義時(shí)賦值,避免重復(fù)代碼,但應(yīng)避免使用可變對(duì)象作為默認(rèn)值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用于通用接口或裝飾器,但應(yīng)謹(jǐn)慎使用以保持可讀性。

解釋Python發(fā)電機(jī)和迭代器。 解釋Python發(fā)電機(jī)和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是實(shí)現(xiàn)__iter__()和__next__()方法的對(duì)象,生成器是簡(jiǎn)化版的迭代器,通過(guò)yield關(guān)鍵字自動(dòng)實(shí)現(xiàn)這些方法。1.迭代器每次調(diào)用next()返回一個(gè)元素,無(wú)更多元素時(shí)拋出StopIteration異常。2.生成器通過(guò)函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無(wú)限序列。3.處理已有集合時(shí)用迭代器,動(dòng)態(tài)生成大數(shù)據(jù)或需惰性求值時(shí)用生成器,如讀取大文件時(shí)逐行加載。注意:列表等可迭代對(duì)象不是迭代器,迭代器到盡頭后需重新創(chuàng)建,生成器只能遍歷一次。

python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

類(lèi)方法是Python中通過(guò)@classmethod裝飾器定義的方法,其第一個(gè)參數(shù)為類(lèi)本身(cls),用于訪問(wèn)或修改類(lèi)狀態(tài)。它可通過(guò)類(lèi)或?qū)嵗{(diào)用,影響的是整個(gè)類(lèi)而非特定實(shí)例;例如在Person類(lèi)中,show_count()方法統(tǒng)計(jì)創(chuàng)建的對(duì)象數(shù)量;定義類(lèi)方法時(shí)需使用@classmethod裝飾器并將首參命名為cls,如change_var(new_value)方法可修改類(lèi)變量;類(lèi)方法與實(shí)例方法(self參數(shù))、靜態(tài)方法(無(wú)自動(dòng)參數(shù))不同,適用于工廠方法、替代構(gòu)造函數(shù)及管理類(lèi)變量等場(chǎng)景;常見(jiàn)用途包括從

如何處理Python中的API身份驗(yàn)證 如何處理Python中的API身份驗(yàn)證 Jul 13, 2025 am 02:22 AM

處理API認(rèn)證的關(guān)鍵在于理解并正確使用認(rèn)證方式。1.APIKey是最簡(jiǎn)單的認(rèn)證方式,通常放在請(qǐng)求頭或URL參數(shù)中;2.BasicAuth使用用戶名和密碼進(jìn)行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過(guò)client_id和client_secret獲取Token,再在請(qǐng)求頭中帶上BearerToken;4.為應(yīng)對(duì)Token過(guò)期,可封裝Token管理類(lèi)自動(dòng)刷新Token;總之,根據(jù)文檔選擇合適方式,并安全存儲(chǔ)密鑰信息是關(guān)鍵。

什么是python魔法方法或dunder方法? 什么是python魔法方法或dunder方法? Jul 04, 2025 am 03:20 AM

Python的magicmethods(或稱dunder方法)是用于定義對(duì)象行為的特殊方法,它們以雙下劃線開(kāi)頭和結(jié)尾。1.它們使對(duì)象能夠響應(yīng)內(nèi)置操作,如加法、比較、字符串表示等;2.常見(jiàn)用例包括對(duì)象初始化與表示(__init__、__repr__、__str__)、算術(shù)運(yùn)算(__add__、__sub__、__mul__)及比較運(yùn)算(__eq__、__lt__);3.使用時(shí)應(yīng)確保其行為符合預(yù)期,例如__repr__應(yīng)返回可重構(gòu)對(duì)象的表達(dá)式,算術(shù)方法應(yīng)返回新實(shí)例;4.應(yīng)避免過(guò)度使用或以令人困惑的方

描述Python中的Python垃圾收集。 描述Python中的Python垃圾收集。 Jul 03, 2025 am 02:07 AM

Python的垃圾回收機(jī)制通過(guò)引用計(jì)數(shù)和周期性垃圾收集來(lái)自動(dòng)管理內(nèi)存。其核心方法是引用計(jì)數(shù),當(dāng)對(duì)象的引用數(shù)為零時(shí)立即釋放內(nèi)存;但無(wú)法處理循環(huán)引用,因此引入了垃圾收集模塊(gc)來(lái)檢測(cè)并清理循環(huán)。垃圾回收通常在程序運(yùn)行中引用計(jì)數(shù)減少、分配與釋放差值超過(guò)閾值或手動(dòng)調(diào)用gc.collect()時(shí)觸發(fā)。用戶可通過(guò)gc.disable()關(guān)閉自動(dòng)回收、gc.collect()手動(dòng)執(zhí)行、gc.set_threshold()調(diào)整閾值以實(shí)現(xiàn)控制。并非所有對(duì)象都參與循環(huán)回收,如不包含引用的對(duì)象由引用計(jì)數(shù)處理,內(nèi)置

Python內(nèi)存管理如何工作? Python內(nèi)存管理如何工作? Jul 04, 2025 am 03:26 AM

Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta

See all articles