初探Python網絡爬蟲:Requests庫
首先打開cmd,輸入pip install requests,下載requests庫
>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> r.status_code
200
>>> r.encoding='utf-8'
>>> r.text
1. r=requests.get(URL)構造一個向服務器請求資源的Request對象,並返回一個包含服務器資源的Response對象
2. r.status_code:HTTP請求返回的狀態,200表示成功,404表示失敗
3. r.text:URL對應的頁面內容
4. r.encoding:網頁的編碼方式
5. r.content:HTTP相應內容的二進制格式
爬取網頁的通用代碼框架
import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=300)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return '產生異常'
if __name__=="__main__":
url="http://www.baidu.com"
#url可以爲任意網址(科學上網....emmmmm')
print(getHTMLText(url))
實例1:爬取京東商品信息
- 我們先上京東官網,找一件商品信息,此文以iPhone XS Max爲例:
代碼
import requests
url="https://item.jd.com/100000287117.html"
try:
r=requests.get(url)
r.raise_for_status
r.encoding=r.apparent_encoding
print(r.text[:1000])
except:
print("爬取失敗")
運行結果
實例2:百度搜索關鍵詞提交
import requests
keyword="Python" #搜索關鍵詞
try:
kv={'wd':keyword} #鍵值對
r=requests.get("http://www.baidu.com/s",params=kv)
print(r.request.url)
r.raise_for_status()
print(len(r.text))
r.encoding=r.apparent_encoding
print(type(r))
except:
print("爬取失敗")
運行截圖
requests.get(url,params=None,**kwargs)
kwargs:控制訪問的參數,均爲可選項
params:字典或字節序列,作爲參數增加到URL中
實例3:從網上爬取圖片
從網上找一張自己喜歡的圖片,右鍵複製圖片地址。
利用Python爬取圖片並保存到當地。
import requests
import os
url="http://thesource.com/wp-content/uploads/2018/04/Migos-1523024180-640x466.jpg"
root="D://pics//"
path=root+url.split('/')[-1]
try:
if not os.path.exists(root):
os.mkdir(root)
if not os.path.exists(path):
r=requests.get(url)
with open(path,'wb') as f:
f.write(r.content)
f.close()
print("文件保存成功")
else:
print("文件已存在")
except:
print("爬取失敗")
註釋:
-
os 模塊提供了非常豐富的方法用來處理文件和目錄
詳情請看:
Python.docs
Python OS 文件/目錄方法 -
檢查某個路徑(前提是你不關心其指向的是文件還是文件夾)是否存在的另一種方法,是使用os.path.exists
-
os.mkdir(root):創建一個目錄
-
with…as…語法具體請看:
理解Python中的with…as…語法-CSDN -
open/文件操作
f=open(’/tmp/hello’,‘w’)
#open(路徑+文件名,讀寫模式)
#讀寫模式:r只讀,r+讀寫,w新建(會覆蓋原有文件),a追加,b二進制文件.常用模式