python 使用 requests 库发送请求及设置代理
生活随笔
收集整理的這篇文章主要介紹了
python 使用 requests 库发送请求及设置代理
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
1、請求網(wǎng)頁時,有的網(wǎng)頁有防機(jī)器人,所以需要設(shè)置 user-agent 標(biāo)識為瀏覽器,就不會被拒絕訪問;
2、當(dāng)訪問國外需要翻墻的網(wǎng)頁時,可以通過設(shè)置代理實現(xiàn)訪問,分為 http 和 https 兩種,另外需要注意 urllib3 版本不要高于 1.26.0,當(dāng)請求出現(xiàn)錯誤(check_hostname requires server_hostname) 或者一直沒響應(yīng)時,可以檢查是否是 urllib3 版本問題;
3、
????????發(fā)送 get 請求時,傳參使用參數(shù)名 params:requests.get(url, headers, params=params)
? ? ? ? 發(fā)送 post 請求時,傳參使用參數(shù)名 data:requests.post(url, headers, data=params)
? ? ? ? 響應(yīng)數(shù)據(jù):
- ?response.status_code? ?# 響應(yīng)的狀態(tài)碼
- ?response.headers? ? ? ? ?# 響應(yīng)的頭信息
- ?response.text? ? ? ? ? ? ? ?# 返回數(shù)據(jù)(字符串)
- ?response.json()? ? ? ? ? ?# 返回數(shù)據(jù)(json 格式)
- response.content? ? ? ? # 返回數(shù)據(jù)(二進(jìn)制數(shù)據(jù))
? 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',]# 頻繁請求某個網(wǎng)址偶爾會報錯請求超時,可采用下面方式降低失敗率,設(shè)置重試次數(shù)為5,會話設(shè)置為不維持連接.requests.adapters.DEFAULT_RETRIES = 5ses = requests.session()ses.keep_alive = False# 隨機(jī)獲取 headersheaders = {'User-Agent': random.choice(user_agent)}# 設(shè)置代理,分為 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')
總結(jié)
以上是生活随笔為你收集整理的python 使用 requests 库发送请求及设置代理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: dlp监控开除员工_说一说DLP的那些事
- 下一篇: websocket python爬虫_p