Python爬蟲連載10-Requests模塊、Proxy代理


一、Request模塊

1.HTTP for Humans,更簡潔更友好

2.繼承了urllib所有的特征

3.底層使用的是urllib3

4.​開源地址:https://github.com/requests/requests

5.中文文檔​:https://requests.readthedocs.io/zh_CN/latest/

6.先安裝這個包:pip install requests

7.get請求

(1)requests.get()

(2)requests.request("get",url)

(3)可以帶有headers和params參數

8.get返回內容

 

import requests

​

#兩種請求

url = "http://www.baidu.com/s?"

rsp = requests.get(url)

# print(rsp.text)
#使用get請求

rsp = requests.request("GET",url)

# print(rsp.text)

#拿到的結果都是一樣的
"""

使用參數headers和params來研究返回結果

"""

kw = {

    "wd":"python中文文檔"

}

headers = {

    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"

}

rsp=requests.get(url,params=kw,headers=headers)

print(rsp.text)

print("=========================")

print(rsp.content)

print("=========================")

print(rsp.url)

print(rsp.encoding)

print(rsp.status_code)

 

二、post

data,headers要求使用dict

 

import requests

from urllib import parse

import json

url = "http://www.baidu.com/s?"

data = {

    "kw":"girl"

}

# data = parse.urlencode(data).encode("utf-8")

headers = {

    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.116 Safari/537.36"

}

rsp = requests.post(url,data=data,headers=headers)

print(rsp.text)

# print(rsp.json())

三、proxy代理

1.代理有可能會報錯,如果使用人數多,考慮到安全問題,可能會被強行關閉

2.用戶驗證

(1)代理驗證​:可能需要HTTP basic Auth

 

proxy = {"http":"china:123456@192.168.1.123:458"}

#格式為   用戶名:密碼@代理地址:端口地址

rsp = requests.get("http://baidu.com",proxies=proxy)

 

 

(2)web客戶端驗證

如果遇到web客戶端驗證,需要添加auth=(用戶名,密碼)

 

auth = {"test","123456"}#授權信息

rsp = requests.get("http://www.baidu.com",auth=auth)

 

 

四、源碼

Reptitle10_1_Requests.py

Reptitle10_2_Post.py

https://github.com/ruigege66/PythonReptile/blob/master/Reptitle10_1_Requests.py

https://github.com/ruigege66/PythonReptile/blob/master/Reptitle10_2_Post.py

2.CSDN:https://blog.csdn.net/weixin_44630050

3.博客園:https://www.cnblogs.com/ruigege0000/

4.歡迎關注微信公眾號:傅里葉變換,個人公眾號,僅用於學習交流,后台回復”禮包“,獲取大數據學習資料

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM