python 爬虫1:发送请求
生活随笔
收集整理的這篇文章主要介紹了
python 爬虫1:发送请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
import socket
import urllib.request
import urllib.parse
import urllib.error# 一個測試用網址,后面是跟的是http請求方式post或get, 當為post時返回json數據,form內是發送過去數據
url = 'http://httpbin.org/post'
headers = {# 偽裝使用瀏覽器,默認為Python-urllib'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36 QIHU 360EE','host': 'httpbin.org'
}
# urllib.request.urlopen()函數的data參數必須是字節流形式,當攜帶了該參數,請求方式默認為post
data = bytes(urllib.parse.urlencode({'word': 'hello'}), 'utf-8')
try:req = urllib.request.Request(url=url, data=data, headers=headers, method='POST')response = urllib.request.urlopen(req)
except urllib.error.URLError as e:if isinstance(e.reason, socket.timeout):print('timeout')else:print(e.reason)exit(100)
else:print(type(response))if response.status == 200: # 當為200是表示請求等到正確響應print(response.getheaders()) # 得到響應頭print(type(response.getheaders()))print(response.getheader('Server'))print(response.read().decode('utf-8')) # 得到響應源碼
class urllib. request. Request ( url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)
第三個參數 headers 是一個字典,它就是請求頭,我們可以在構造請求時通過 headers 參數直 接構造,也可以通過調用請求實例的 add_header()方法添加。
第四個參數 origin_req_host 指的是請求方的 host名稱或者 IP 地址。
第五個參數unveri干iable表示這個請求是否是無法驗證的,默認是 False,意思就是說用戶沒 有足夠權限來選擇接收這個請求的結果。 例如,我們請求一個 HTML 文檔中的圖片,但是我 們沒有向動抓取圖像的權限,這時 unverifiable 的值就是 True。
總結
以上是生活随笔為你收集整理的python 爬虫1:发送请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: for in range语句_Pytho
- 下一篇: python 循环写文件_python-