網(wǎng)站優(yōu)化推廣排名seo的關(guān)鍵詞無需
這個庫比我們上次說的 urllib 可是要牛逼一丟丟的。通過它我們可以用更少的代碼,模擬瀏覽器操作。
不多說,直接上手代碼。
requests 常見用法
mport requests# get請求網(wǎng)站
r = requests.get('https://www.baidu.com/')
# 獲取服務(wù)器響應(yīng)文本內(nèi)容
r.text
# 查看編碼格式
r.encoding
# 獲取字節(jié)響應(yīng)內(nèi)容
r.content
# 獲取響應(yīng)碼 200
r.status_code
# 獲取響應(yīng)頭
r.headers
# 獲取 Json 響應(yīng)內(nèi)容
r.json()
# 獲取 socket 流響應(yīng)內(nèi)容
r.raw
r.raw.read(10)
# Post請求 當(dāng)你想要一個鍵里面添加多個值的時候
payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
payload_dict = {'key1': ['value1', 'value2']}
r2 = requests.post('https://httpbin.org/post', data=payload_dict)
print(r1.text)
r1.text == r2.text # True
# 請求的時候用 json 作為參數(shù)
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, json=payload)
# 上傳文件
url = 'https://httpbin.org/post'
files = {'file': open('learn_python3_spider-master/wechat_moment.py', 'rb')}
r = requests.post(url, files=files)
r.text
# 獲取 cookie 信息
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']
# 發(fā)送 cookie 信息
url = 'https://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
r.text
# 設(shè)置超時
requests.get('https://github.com/', timeout=0.001)# post請求
r = requests.post('https://httpbin.org/post', data = {'key':'value'})# 其它亂七八糟的 Http 請求
r = requests.put('https://httpbin.org/put', data = {'key':'value'})
r = requests.delete('https://httpbin.org/delete')
r = requests.head('https://httpbin.org/get')
r = requests.options('https://httpbin.org/get')
post 和 get 的區(qū)別
get請求一般用來請求獲取數(shù)據(jù),post請求一般作為發(fā)送數(shù)據(jù)到后臺,傳遞數(shù)據(jù),創(chuàng)建數(shù)據(jù)