python 使用 requests 库发送请求及设置代理
生活随笔
收集整理的這篇文章主要介紹了
python 使用 requests 库发送请求及设置代理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、請求網頁時,有的網頁有防機器人,所以需要設置 user-agent 標識為瀏覽器,就不會被拒絕訪問;
2、當訪問國外需要翻墻的網頁時,可以通過設置代理實現訪問,分為 http 和 https 兩種,另外需要注意 urllib3 版本不要高于 1.26.0,當請求出現錯誤(check_hostname requires server_hostname) 或者一直沒響應時,可以檢查是否是 urllib3 版本問題;
3、
????????發送 get 請求時,傳參使用參數名 params:requests.get(url, headers, params=params)
? ? ? ? 發送 post 請求時,傳參使用參數名 data:requests.post(url, headers, data=params)
? ? ? ? 響應數據:
- ?response.status_code? ?# 響應的狀態碼
- ?response.headers? ? ? ? ?# 響應的頭信息
- ?response.text? ? ? ? ? ? ? ?# 返回數據(字符串)
- ?response.json()? ? ? ? ? ?# 返回數據(json 格式)
- response.content? ? ? ? # 返回數據(二進制數據)
? import requests import randomdef request_url(url):user_agent = ['Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/94.0.4606.61 Safari/537.36','Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ''Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38',]# 頻繁請求某個網址偶爾會報錯請求超時,可采用下面方式降低失敗率,設置重試次數為5,會話設置為不維持連接.requests.adapters.DEFAULT_RETRIES = 5ses = requests.session()ses.keep_alive = False# 隨機獲取 headersheaders = {'User-Agent': random.choice(user_agent)}# 設置代理,分為 http 和 httpsproxies = {"http": "http://127.0.0.1:1080","https": "https://127.0.0.1:1080"}try:response = ses.get(url=url, headers=headers, proxies=proxies)except requests.exceptions.RequestException as e:print(f'request url {url} occurs error')print(e)print(response.status_code, response.headers)# 獲取文件大小 def get_file_size(file):file_size = int(requests.head(file, headers=self.headers).headers['Content-Length'])return file_sizeif __name__ == '__main__':request_url(url='http://www.baidu.com')
總結
以上是生活随笔為你收集整理的python 使用 requests 库发送请求及设置代理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dlp监控开除员工_说一说DLP的那些事
- 下一篇: python画椭圆形_Python易学就