網(wǎng)絡爬蟲入門 (一) Requests的使用

一、簡介

Requests是用Python語言編寫,基于urllib,采用Apache2 Licensed開原協(xié)議的HTTP庫。相對urllib使用起來更加方便,可以節(jié)約大量工作。

安裝方法:

  • conda install requests或者pip install requests
  • conda list或者pip list查看環(huán)境內(nèi)是否已安裝

使用help(requests)方法可以查看requests的幫助文檔

二、請求方式

1、 get請求

import requests
res = requests.get("http://www.baidu.com")#get請求
print(res)#響應
print(res.status_code)#返回請求的狀態(tài)碼,成功時為200
print(res.text)
print(res.encoding)#字符編碼
print(res.cookies)
print(res.headers)#響應頭
#將請求到的結(jié)果保存到當前目錄下
# with open("./test.html", "w", encoding="utf-8") as file:
#     file.write(res.text)

2、post請求

import requests
params = {"key1": "value1", "key2": "value2"}
try:
    response = requests.post("http://httpbin.org", data=params)
    print(response.status_code)
    print(response.text)
except requests.exceptions.ConnectionError as e:
    print("服務器連接失敗")

三、常用API

1、設置請求頭

在實際爬取網(wǎng)站的過程中,經(jīng)常會碰到服務器的反爬策略,其中之一的解決方法就是模擬瀏覽器的請求頭,
可以在請求

import requests
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36"}
proxies = {
    "http":"122.72.32.73:80",
    "https":"58.67.159.50:80"
}
#進行get請求的同時設置請求頭和代理IP
response = requests.get("http://www.tmall.com", headers=headers, proxies=proxies)
print(response.status_code)
print(response.text)

總體來說使用難度較低,可以配合官方文檔一起學習
http://docs.python-requests.org/en/latest/user/quickstart.html

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容