一、Request請求偽裝解析
#UA:User-Agent(請求載體身份標識)
#UA檢測:門戶網站的服務器會檢測對應請求的載體身份標識,如果檢測到請求的載體身份呢標識為某一款瀏覽器,說明該請求是一個正常的請求,
#但是如果檢測到請求的載體身份標識不是基于某一款瀏覽器的,則表示為不正常的請求(爬蟲),則服務器端就很有可能拒絕該請求。
#UA偽裝:讓爬蟲對應的請求載體身份標識偽裝成某一款瀏覽器
import requests
#執行UA偽裝,寫入UA信息,封裝到字典中
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:122.0) Gecko/20100101 Firefox/122.0'
}
url = 'https://www.sogou.com/web'
#處理url攜帶的參數:封裝到字典中
kw = input('enter a word:')
param = {'query':kw
}
#對指定的url發起的請求對應的url添加攜帶的參數信息,并且于請求過程中處理了參數,
response = requests.get(url=url,params=param,headers=headers)
page_text = response.text
fileName = kw+'.html'
with open(fileName,'w',encoding='utf-8') as fp:fp.write(page_text)
print(fileName,'保存成功!!!')
二、HTTP請求報文解析
HTTP 請求報文(Request Message)是客戶端發給服務器的數據包,通常由 起始行(Start Line)、請求頭(Headers) 和 可選的消息體(Body) 三部分組成。
1. 起始行(Start Line)
分為三部分,用空格分隔:
GET /index.html HTTP/1.1
方法(Method):如 GET、POST、PUT、DELETE 等,表示操作類型。
路徑(Path):請求的資源路徑(如 /index.html),可包含查詢參數(如 /api?key=123)。
協議版本(HTTP Version):如 HTTP/1.1 或 HTTP/2。
2. 請求頭(Headers)
鍵值對形式(Key: Value),每行一個,常見字段:
字段名 | 示例值 | 作用說明 |
---|---|---|
Host | www.example.com | 目標主機域名(HTTP/1.1 必須字段) |
User-Agent | Mozilla/5.0 (Windows NT 10.0) | 客戶端軟件標識 |
Accept | text/html,application/xhtml+xml | 客戶端能處理的媒體類型 |
Accept-Encoding | gzip, deflate | 支持的壓縮算法 |
Content-Type | application/json | Body 的數據類型(POST/PUT 必填) |
Content-Length | 348 | Body 的字節長度 |
Authorization | Bearer token123 | 身份驗證憑證 |
Cookie | sessionid=abc123 | 攜帶的 Cookie 數據 |
Cache-Control | no-cache | 緩存控制策略 |
3. 消息體(Body)
可選部分,通常用于 POST/PUT 請求,攜帶實際數據。例如:
表單提交(Content-Type: application/x-www-form-urlencoded):
username=tom&password=123456
JSON 數據(Content-Type: application/json):
{"username": "tom", "password": "123456"}
完整示例:
POST /api/login HTTP/1.1
Host: example.com
User-Agent: curl/7.68.0
Accept: application/json
Content-Type: application/json
Content-Length: 43{"username": "alice", "password": "secret123"}