1. 程式人生 > >python之requests

python之requests

into code 判斷 tex webkit tom pen status get

requests

requests是python實現的簡單易用的HTTP庫,使用起來比urllib簡潔很多

用法

各種請求方式,最好加上頭信息和異常判斷

import requests

requests.get(http://httpbin.org/get)
requests.post(http://httpbin.org/post)
requests.put(http://httpbin.org/put)
requests.delete(http://httpbin.org/delete)
requests.head(http://httpbin.org/get)
requests.options(
http://httpbin.org/get)

url參數

1.直接放在url

import requests

response = requests.get(http://httpbin.org/get?name=gemey&age=22)
print(response.text)

2.放在一個字典中

import requests

data = {
    name: tom,
    age: 20
}

response = requests.get(http://httpbin.org/get, params=data)
print(response.text)

添加頭信息

import requests
heads = {}
heads[User-Agent] = Mozilla/5.0                            (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50                            (KHTML, like Gecko) Version/5.1 Safari/534.50
 response = requests.get(http://www.baidu.com,headers=headers)

屬性

r.status_code

http請求的返回狀態,200表示連接成功,404表示連接失敗

r.text

http響應內容的字符串形式,url對應的頁面內容

r.encoding

從HTTP header中猜測的響應內容編碼方式

r.apparent_encoding

從內容分析出的響應內容的編碼方式(備選編碼方式)

r.content

HTTP響應內容的二進制形式

r.headers

http響應內容的頭部內容

r..cookies

獲取cookie

r.Session

會話維持

解析json

import requests

response = requests.get(http://httpbin.org/get)
print(response.text)
print(response.json())  #response.json()方法同json.loads(response.text)
print(type(response.json()))

保存二進制文件

import requests

response = requests.get(http://img.ivsky.com/img/tupian/pre/201708/30/kekeersitao-002.jpg)
b = response.content
with open(F://fengjing.jpg,wb) as f:
    f.write(b)

python之requests