导入httpx
In [25]: import httpx
获取一个网页
In [26]: r = httpx.get("https://httpbin.org/get")
In [27]: r
Out[27]:
同样,发送HTTP POST请求:
In [28]: r = httpx.post("https://httpbin.org/post", data={"key": "value"})
In [29]: r
Out[29]:
PUT,DELETE,HEAD和OPTIONS请求都遵循相同的方式:
In [35]: r = httpx.put("https://httpbin.org/put", data={"key": "value"})
In [36]: r = httpx.delete("https://httpbin.org/delete")
In [37]: r = httpx.head("https://httpbin.org/get")
In [38]: r = httpx.options("https://httpbin.org/get")
在URL中传递参数
在请求URL中传递查询参数,请使用params关键字 In [41]: r = httpx.get("https://httpbin.org/get", params=params)
In [42]: r
Out[42]:
检查发出请求结果的URL
2. 将项目列表作为值传递
In [44]: params = {"key1": "value2", "key2": ["value2", "value3"]}
In [45]: r = httpx.get("https://httpbin.org/get", params=params)
### 响应内容
HTTPX将自动处理响应内容解码为`Unicode`文本
In [52]: r = httpx.get("https://www.example.org/")
In [53]: r.text
Out[53]: '\n\n
\n Example Domain\n\n \n \n \n \n\n\n\nExample Domain
\nThis domain is for use in illustrative examples in documents. You may use this\n domain in literature without prior coordination or asking for permission.
\n \n解码
In [54]: r.encoding
Out[54]: 'UTF-8'
设置需要使用的编码
In [55]: r.encoding = "ISO-8859-1"
In [56]: print(r.headers, r.http_version, r.url, r.status_code)
Headers({'content-encoding': 'gzip', 'age': '532553', 'cache-control': 'max-age=604800', 'content-type': 'text/html; charset=UTF-8', 'date': 'Sat, 06 Jun 2020 04