Python中網(wǎng)絡(luò)請求的12種方式
1. 使用requests模塊的基礎(chǔ)請求
import requests; response = requests.get('https://api.example.com/data')
這是最基本的網(wǎng)絡(luò)請求,用requests.get()
函數(shù)向指定URL發(fā)送GET請求,response
里裝的就是響應(yīng)數(shù)據(jù)。
2. GET請求帶參數(shù)
params = {'key': 'value'}; response = requests.get('https://example.com/search', params=params)
通過字典params
傳遞查詢參數(shù),簡單又高效。
3. POST請求發(fā)送數(shù)據(jù)
data = {'username': 'learner'}; response = requests.post('https://example.com/login', data=data)
POST請求常用于提交數(shù)據(jù),比如登錄表單,這里用data
字典攜帶你的信息。
4. 設(shè)置請求頭
headers = {'User-Agent': 'MyBot/0.1'}; response = requests.get('https://example.com', headers=headers)
模擬瀏覽器或添加特定的請求頭,有時候是訪問某些網(wǎng)站的關(guān)鍵。
5. 處理JSON響應(yīng)
response = requests.get('https://api.example.com/data'); print(response.json())
直接用.json()
方法解析JSON格式的響應(yīng),方便快捷。
6. 下載文件
with open('image.jpg', 'wb') as f: f.write(requests.get('https://example.com/image.jpg', stream=True).content)
流式下載大文件,避免內(nèi)存爆棚,記得以二進制模式打開文件哦。
7. 超時設(shè)置
response = requests.get('https://slow.example.com', timeout=3)
耐心有限,3秒內(nèi)沒響應(yīng)就放棄,避免程序掛起。
8. 使用代理
proxies = {'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8080'}; response = requests.get('https://example.com', proxies=proxies)
當你需要通過代理服務(wù)器訪問時,這個技巧很實用。
9. 自動處理重定向
response = requests.get('https://redirect-me.example.com', allow_redirects=False)
默認情況下會自動重定向,加allow_redirects=False
可以控制是否跟隨重定向。
10. 發(fā)送認證信息
response = requests.get('https://protected.example.com', auth=('user', 'pass'))
問需要認證的頁面,用戶名密碼一提交,輕松搞定。
11. 會話管理(保持Cookie)
with requests.Session() as s: s.get('https://login.example.com') response = s.get('https://profile.example.com')
使用Session對象,可以維持登錄狀態(tài),訪問受限資源。
12. 錯誤處理
try: response = requests.get('https://never.exists.com') except requests.exceptions.RequestException as e: print(e)
優(yōu)雅地處理請求過程中可能遇到的錯誤,讓你的程序更加健壯。
實戰(zhàn)案例:網(wǎng)頁內(nèi)容抓取
想象一下,你想從一個博客網(wǎng)站上抓取最新的文章標題。假設(shè)這個網(wǎng)站的每篇文章鏈接都在一個類名為'article-title'的HTML元素中。你可以這樣做:
from bs4 import BeautifulSoup; import requests url = 'https://example-blog.com/latest' response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') titles = [title.text for title in soup.find_all(class_='article-title')] print(titles)
這段代碼首先發(fā)送GET請求獲取網(wǎng)頁內(nèi)容,然后使用BeautifulSoup解析HTML,最后通過列表推導(dǎo)式提取所有文章標題。這就是一個簡單的網(wǎng)絡(luò)爬蟲雛形。
練習技巧與方法提示
分步調(diào)試:在復(fù)雜的請求邏輯中,分步執(zhí)行并打印中間結(jié)果,有助于理解流程。
**使用
requests.Session
**:在頻繁請求同一站點時,使用Session可以提高效率,減少握手時間。錯誤日志:記錄請求過程中的錯誤,有助于排查問題??梢允褂肞ython的logging模塊。
注意事項
遵守Robots協(xié)議(robots.txt):尊重網(wǎng)站規(guī)則,不爬取禁止抓取的內(nèi)容。
請求頻率:合理控制請求間隔,避免對目標網(wǎng)站造成過大壓力,可能導(dǎo)致IP被封禁。
數(shù)據(jù)處理:獲取的數(shù)據(jù)可能需要清洗和格式化,確保數(shù)據(jù)質(zhì)量。
安全性:在處理HTTP請求時,注意SSL證書驗證,防止中間人攻擊。
高級技巧:異步請求
隨著Python的asyncio庫的普及,異步請求成為提高效率的新方式。雖然不是“一行代碼”,但了解其重要性是必要的。
import aiohttp import asyncio async def fetch(session, url): async with session.get(url) as response: return await response.text() async def main(): async with aiohttp.ClientSession() as session: html = await fetch(session, 'https://example.com') print(html) loop = asyncio.get_event_loop() loop.run_until_complete(main())
這段代碼展示了如何使用aiohttp庫進行異步HTTP請求,大幅提升了并發(fā)請求的能力,適用于大量請求的場景。
以上就是Python中網(wǎng)絡(luò)請求的12種方式的詳細內(nèi)容,更多關(guān)于Python網(wǎng)絡(luò)請求的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python的Tornado框架實現(xiàn)圖片上傳及圖片大小修改功能
Tornado是一個異步的Python Web開發(fā)框架,同時也是一個優(yōu)秀的異步服務(wù)器開發(fā)庫,這里我們將來講解一下Python的Tornado框架實現(xiàn)圖片上傳及圖片大小修改功能方面的一些重點:2016-06-06tensorflow 利用expand_dims和squeeze擴展和壓縮tensor維度方式
今天小編就為大家分享一篇tensorflow 利用expand_dims和squeeze擴展和壓縮tensor維度方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02