使用Python爬蟲庫requests發(fā)送請求、傳遞URL參數、定制headers
更新時間:2020年01月25日 11:50:39 作者:BQW_
今天為大家介紹一下Python爬蟲庫requests的發(fā)送請求、傳遞URL參數、定制headers的基礎使用方法
首先我們先引入requests模塊
import requests
一、發(fā)送請求
r = requests.get('https://api.github.com/events') # GET請求
r = requests.post('http://httpbin.org/post', data = {'key':'value'}) # POST請求
r = requests.put('http://httpbin.org/put', data = {'key':'value'}) # PUT請求
r = requests.delete('http://httpbin.org/delete') # DELETE請求
r = requests.head('http://httpbin.org/get') # HEAD請求
r = requests.options('http://httpbin.org/get') # OPTIONS請求
type(r)
requests.models.Response
二、傳遞URL參數
URL傳遞參數的形式為:httpbin.org/get?key=val。但是手動的構造很麻煩,這是可以使用params參數來方便的構造帶參數URL。
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
print(r.url)
http://httpbin.org/get?key1=value1&key2=value2
同一個key可以有多個value
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
三、定制headers
只需要將一個dict傳遞給headers參數便可以定制headers
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
更多關于Python爬蟲庫requests的使用方法請點擊下面的相關鏈接
相關文章
對pandas中iloc,loc取數據差別及按條件取值的方法詳解
今天小編就為大家分享一篇對pandas中iloc,loc取數據差別及按條件取值的方法詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-11-11

