python 爬蟲系列02 認識 requests

2021-08-07 17:51:52 字數 2318 閱讀 9810

本系列所有文章基於 python3.5.2

requests 是基於 urllib 的三方模組,相比於 uillib, 操作更簡潔,功能更強大,而且支援 python3

get

import requests

r = requests.get(url='')

print(r.status_code)

print(r.text)

得到如下結果:

200

...name="keywords"

name="description"

...

帶引數的 get 請求,這裡請求李毅吧的首頁

import requests

params =

r = requests.get(url='', params=params)

print(r.status_code)

print(r.text)

得到如下結果:

200

..."utf-8">

"keywords" content="李毅,網友俱樂部,貼吧,三百六十行,神武">

...

post

post 方法與 get 類似,直接呼叫即可

r = requests.post(url='', params=params)
如果post上傳資料,資料轉換為 bytes 放在 data 字段即可

import requests

import json

upload_url =

'***'

r = requests.post(upload_url, data

=json.dumps())

headers

加上 http 請求頭也很簡單,只需把各個引數作為寫入 dict 傳給 headers 引數即可

下面模擬瀏覽器請求中國天氣網資料

import requests

url = ''

header =

req = requests.get(url, headers=header)

req.encoding = 'utf-8'

# 防止亂碼

print(req.status_code)

print(req.text)

得到如下 http 響應:

200

..."content-type" content="text/html; charset=utf-8" />

【北京天氣】北京天氣預報,藍天,藍天預報,霧霾,霧霾消散,天氣預報一周,天氣預報15天查詢

...

異常, json 解碼
url = ''

# **ip位址庫api

try:

r = requests.get(url, params=, timeout=5)

r.raise_for_status() # 如果響應狀態碼不是 200,就主動丟擲異常

except requests.requestexception as e:

print(e)

else:

result = r.json() # requests中內建的json解碼器

print(type(result), result, sep='\n')

得到結果:

}
cookies

如果某個響應中包含 cookie ,可以快速的訪問他們

import requests

r = requests.get('', timeout=5)

print(tuple(r.cookies))

得到如下結果:

...要想傳送你的 cookies 到伺服器,可以使用 cookies 引數:

cookies =  # 具體內容可用 fiddler 抓包獲取

r = requests.get('', cookies=cookies,timeout=5)

print(r.status_code)

一 Python爬蟲 認識爬蟲

爬蟲是什麼 爬取網際網路上的資訊 資料探勘 資料清洗 得到有效的資訊 爬蟲分類 抓取網頁 資料儲存 預處理 提供檢索,排名 前端 網頁展現 中間層 資料處理 資料庫 資料儲存 伺服器 響應 客戶端 請求 基本格式 scheme host port path query string anchor s...

Python爬蟲系列

部落格 python,爬蟲 由於近來學 lan 業 ai 繁 fa 忙 zuo 快乙個月沒有更新部落格了。這周完成了兩門課的結課考試,現下時間開始變得充裕。準備梳理一下前段時間學習的關於python爬蟲的內容,權當複習鞏固知識。而初次學習時遇到的疑難雜症,那時候的應對策略是抓大放下,在這梳理過程會下...

python爬蟲入門初步認識

python簡單的爬蟲技術,這裡我用的是python3.x版面進行研究,主要對兩個python庫進行操作。在此之前你需要安裝python3.x環境 1 urllib python3.x官方基礎模組 2 beautifulsoup4 python3.x第三方模組 使用前需要安裝beautifulsou...