手机版python3.6.6的requests库下载_Python爬虫之Python3.6 Requests库的基本使用方法
Python爬蟲之Python3.6 Requests庫的基本使用方法
未分類
在使用Python過程中,使用http處理各種請求是我們繞不過去的,在Python中開發爬蟲用來抓取各種網絡上的資源,就必須得使用發送網絡請求獲取我們想要的資源。
Requests 是 Python 的一個強大的HTTP庫,里面封裝了我們用來發送網絡請求的各種方法和函數,來方便我們更加方便的編程。安裝 Requests
$ pip install requests
如果你還沒有安裝 pip 那么自己去google一下怎么安裝pip吧。
如何使用Requests
您可以查看Requests中文文檔進行學習操作。
常用的Requests庫使用
def get(url, params=None, **kwargs):
req = requests.get('http://www.pandait.me')
print(req)
output:
如果我們使用一個不能訪問的網址進行請求,這時候會報錯:
try:
req = requests.get('http://www.pandaitxx.me')
except BaseException as ex:
print(ex.args)
output:(MaxRetryError("HTTPConnectionPool(host='www.pandaitxx.me', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))",),)
具體try except的用法可以自行去搜索處理錯誤。
發送請求,返回輸出結果/HTML:
print(req.text)
print(req.content) 以編碼的方式輸出
請求類型包括:POST,GET,PUT,DELETE,HEAD 以及 OPTIONS
傳URL參數進行請求
datapram = {'key1':"123","key2":"pandait"}
req = requests.get('http://www.pandait.me',datapram)
print(req.url)
output:http://www.pandait.me/?key1=123&key2=pandait
HTTP請求頭
{'Server': 'nginx/1.6.2',
'Date': 'Tue, 16 May 2017 04:52:23 GMT',
'Content-Type': 'text/html; charset=UTF-8',
'Transfer-Encoding': 'chunked',
'Connection': 'keep-alive',
'X-Powered-By': 'PHP/5.4.45',
'X-Pingback': 'http://www.pandait.me/action/xmlrpc'}
可以作為參數進行傳遞,如:
headers = {'user-agent':'....'}
r = requests.get('http://www.pandait.me',headers = headers)
以上就是本文的一些內容,只是簡單介紹和記錄Python Requests庫的基本用法,點擊查看更多 Python Requests高級用法
總結
以上是生活随笔為你收集整理的手机版python3.6.6的requests库下载_Python爬虫之Python3.6 Requests库的基本使用方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 给.net初学者的一些建议(共勉之)[转
- 下一篇: python案例源码_【python】p