python requests笔记

导入

import requests
  • 1

请求类型

requests.request(method, url, **kwargs)
  • 1

• method – 请求的方法 
• url – 请求的url 
• params – url参数,字典或字节格式 
• data – 请求体中的数据,字典或字节或file-like对象 
• json – 请求体中的数据,json格式 
• headers – 请求头,字典格式 
• cookies – 用于请求的cookies,字典或CookieJar对象 
• files – (optional) Dictionary of ‘name’: file-like-objects (or {‘name’: file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple (‘filename’, fileobj), 3-tuple (‘filename’, fileobj, ‘content_type’) or a 4-tuple (‘filename’, fileobj, ‘content_type’, custom_headers), where ‘content-type’ is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file. 
• auth – (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth. 
• timeout (float or tuple) – 超时, 浮点型,或(connect timeout, read timeout)元组 
• allow_redirects (bool) – 布尔型,是否允许POST/PUT/DELETE访问的重定向. 
• proxies – (optional) Dictionary mapping protocol to the URL of the proxy. 
• verify – (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to True. 
• stream – (optional) if False, the response content will be immediately downloaded. 
• cert – (optional) if String, path to ssl client cert file (.pem). If Tuple, (‘cert’, ‘key’) pair.

requests.head(url, **kwargs)
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.delete(url, **kwargs)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

这六种请求,均返回Response对象

参考: http://docs.python-requests.org/zh_CN/latest/api.html#id2

传递url参数

payload = {'key1': 'value1', 'key2': 'value2'}
requests.get("http://httpbin.org/get", params=payload)
http://httpbin.org/get?key2=value2&key1=value1

payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
requests.get('http://httpbin.org/get', params=payload)
http://httpbin.org/get?key1=value1&key2=value2&key2=value3
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

定制请求头

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
requests.get(url, headers=headers)
  • 1
  • 2
  • 3

POST请求

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

r = requests.post(url, json=payload)
  • 1

响应状态

r = requests.get('http://httpbin.org/get')
r.status_code # 查看响应状态码
r.status_code == requests.codes.ok # 判断响应状态码
Response.raise_for_status() # 当响应状态码非200时,抛出异常
  • 1
  • 2
  • 3
  • 4

cookies

url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
requests.get(url, cookies=cookies)
  • 1
  • 2
  • 3

重定向

requests.get('http://github.com', allow_redirects=False) # 禁用重定向
r.status_code # 如果该响应是重定向,并且你禁用了重定向,那么该返回状态码为301
  • 1
  • 2

超时

requests.get('http://github.com', timeout=0.001) # 设置请求超时秒数, 仅对连接过程有效,与响应体的下载无关.
  • 1

异常

requests.RequestException(*args, **kwargs)请求时发生的不确定性异常
requests.ConnectionError(*args, **kwargs)链接错误
requests.HTTPError(*args, **kwargs)http错误, 响应状态码不为200,Response.raise_for_status()抛出HTTPError
requests.URLRequired(*args, **kwargs)没有有效的url
requests.TooManyRedirects(*args, **kwargs) 请求超过了设定的最大重定向次数
requests.ConnectTimeout(*args, **kwargs)连接远程服务器超时
requests.ReadTimeout(*args, **kwargs)服务器没响应
requests.Timeout(*args, **kwargs)请求超时,捕获该异常将同时捕获ConnectTimeout和ReadTimeout.
requests所有显式异常都继承自requests.exceptions.RequestException
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

参考: http://docs.python-requests.org/zh_CN/latest/api.html#id3

会话

跨请求保持cookies和配置 
基本用法:

s = requests.Session()
s.get('http://httpbin.org/get')
  • 1
  • 2

上下文管理器:

with requests.Session() as s:
    s.get('http://httpbin.org/get')
  • 1
  • 2

参考: http://docs.python-requests.org/zh_CN/latest/api.html#id4

Response对象

r.url                    url地址
r.encoding              当访问r.text时,用于解码的编码
r.text                  返回的内容,根据r.encoding解码
r.content               响应的内容,以字节为单位
r.json()                解码json格式数据
r.status_code           响应状态码
r.headers               服务器响应头
r.cookies                服务器返回的CookieJar对象
r.history               重定向记录
r.request               这个Response对象对应的PreparedRequest对象
    r.request.headers       获取请求头部
r.raise_for_status()    抛出异常
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
参数和data有什么区别? 在python requests库的request()函数中,params和data都是可选参数,用于向服务器发送请求时传递参数的。区别如下: params参数用于GET请求,将参数以键值对的形式添加到URL的末尾。例如,使用params参数可以向百度搜索发送一个GET请求,搜索关键词为'python',示例代码如下: ``` import requests r = requests.get(url='http://dict.baidu.com/s', params={'wd': 'python'}) ``` data参数用于POST请求,将参数以字典的形式作为请求的主体发送到服务器。例如,向百度贴吧发送一个POST请求,搜索关键词为'python',并且显示结果的页数为2,示例代码如下: ``` import requests from fake_useragent import UserAgent url = 'http://tieba.baidu.com/f?' # 基准url地址 data = {"kw": "python", "pn": 50} # data参数 headers = {'User-Agent': UserAgent().random} # headers参数 html = requests.post(url=url, data=data, headers=headers, verify=False).text # 发送POST请求 print(html) # 打印响应内容 ``` 总结来说,params参数适用于GET请求,将参数添加到URL的末尾;data参数适用于POST请求,将参数作为请求的主体发送到服务器。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python requests模块详解](https://blog.csdn.net/lx1315998513/article/details/105746615)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [【Python_requests学习笔记(三)】requests模块中params参数用法](https://blog.csdn.net/sallyyellow/article/details/129686842)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [python requests包的request()函数中的参数-params和data的区别介绍](https://download.csdn.net/download/weixin_38500572/12852315)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值