美文网首页
Python Requests 快速上手

Python Requests 快速上手

作者: 我是来捕鱼的 | 来源:发表于2018-04-09 19:28 被阅读7次

Requests官方文档
Http协议简析

一、发送请求

  1. 首先导入Requests模块
impose requests 
  1. 尝试获取某个网页的HTML代码
r = requests.get('www.zhihu.com')

这样我们就得到了一个名为r的Requests对象,当然我们也可以用post put等请求方法。

二、传递URL参数

可以手工构建URL例如

https://www.zhihu.com/search?type=content&q=123

表示想搜索123的内容

当然Requests也提供了构建方法

payload = {'type':'content','q':'123'}
r = requests.get("www.zhihu.com/search",params = payload)

三、定制请求头

url = 'www.zhihu.com'
headers = {'user-agent':'my_app/0.0.1'}
r = requests.get(url,headers = headers)

四、响应状态码

可以通过得到的Requests对象来查看响应状态码

r = requests.get('www.zhihu.com')
status_code = r.status_code

Requests还附带了一个内置的状态查询对象

r.status_code == requests.codes.ok

五、Cookie

访问Cookie

url = 'www.zhihu.com'
r = requests.get(url)
r.cookies
r.cookies['example_cookie_name']

发送Cookies到服务器,可以使用cookies参数:

url = 'http://httpbin.org/cookies'
 cookies = dict(cookies_are='working')
 r = requests.get(url, cookies=cookies)
 r.text
'{"cookies": {"cookies_are": "working"}}'

六、超时

使用timeout参数设定多少秒之后停止等待响应

requests.get('www.zhihu,com',timeout = 0.01)

相关文章

网友评论

      本文标题:Python Requests 快速上手

      本文链接:https://www.haomeiwen.com/subject/xguthftx.html