requests请求模块

简介

Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,Requests它会比urllib更加方便,可以节约我们大量的工作。

安装
pip install requests

使用

先上一串代码

import requests
 
response  = requests.get("https://www.baidu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
#获得响应头内容
print(response.headers)
print(response.headers['content-type'])
#还可以用这种方式获取请求头内容
print(response.request.headers)
 # 解决乱码问题
response.enconding = "utf-8' 
print(response.text)
 
print(response.cookies)
 
print(response.content)
print(response.content.decode("utf-8"))
  • response.text返回的是Unicode格式,通常需要转换为utf-8格式,否则就是乱码。
  • response.content是二进制模式,可以下载视频之类的,如果想看的话需要decode成utf-8格式。
  • 不管是通过response.content.decode("utf-8)的方式还是通过response.encoding="utf-8"的方式都可以避免乱码的问题发生

各种请求方式

import requests
requests.post("http://httpbin.org/post") #发送post请求
requests.put("http://httpbin.org/put")  #提交修改信息
requests.patch("http://httpbin.org/put")  #提交局部修改的请求
requests.delete("http://httpbin.org/delete") # 提交删除请求
requests.head("http://httpbin.org/get") #获取HTML头部信息
requests.options("http://httpbin.org/get")  

基本GET

import requests
 
url = 'https://www.baidu.com/'
response = requests.get(url)
print(response.text)

带参数的GET请求

如果想查询http://httpbin.org/get页面的具体参数,需要在url里面加上,例如我想看有没有Host=httpbin.org这条数据,url形式应该是http://httpbin.org/get?Host=httpbin.org

下面提交的数据是往这个地址传送data里面的数据。

# 带参数的get请求
 
import requests
url = 'https://tieba.baidu.com/f?'
params = {'kw':'大学吧', 'pn':'3'}
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64)'}
# 开始请求
html = requests.get(url=url, params=params, headers=headers).text
print(html)

Json数据

从下面的数据中我们可以得出,如果结果:

1、requests中response.json()方法等同于json.loads(response.text)方法

import requests
import json
 
response = requests.get("http://httpbin.org/get")
print(type(response.text))
print(response.json())
print(json.loads(response.text))
print(type(response.json())
print(response.json()['data'])

获取二进制数据

在上面提到了response.content,这样获取的数据是二进制数据,同样的这个方法也可以用于下载图片以及视频资源

添加header

首先说,为什么要加header(头部信息)呢?例如下面,我们试图访问知乎的登录页面(当然大家都你要是不登录知乎,就看不到里面的内容),我们试试不加header信息会报什么错。

import requests
 
url = 'https://www.zhihu.com/'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
}
response = requests.get(url,headers=headers)
print(response.text)

基本post请求:

通过post把数据提交到url地址,等同于一字典的形式提交form表单里面的数据

import requests
 
url = 'http://httpbin.org/post'
data = {
    'name':'jack',
    'age':'23'
    }
response = requests.post(url,data=data)
print(response.text)

结果:

{
  "args": {},
  "data": "",
  "files": {},
  "form": {
    "age": "23",
    "name": "jack"
  },
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip, deflate",
    "Connection": "close",
    "Content-Length": "16",
    "Content-Type": "application/x-www-form-urlencoded",
    "Host": "httpbin.org",
    "User-Agent": "python-requests/2.13.0"
  },
  "json": null,
  "origin": "118.144.137.95",
  "url": "http://httpbin.org/post"
}
  • 语法结构

    requests.post(url,data=None,json=None)

  • 参数说明

    • url: 需要爬取的网站的网址
    • data: 请求数据
    • json: json格式的数据
  • 案例:

    import requests
    url='https://www.xslou.com/login.php'
    data={'username':'18600605736', 'password':'57365736', 'action':'login'}
    resp = requests.post(url,data)
    resp.encoding='gb2312'
    print('响应状态码:', resp.status_code)   # 200
    print('响应内容', resp.text)        # <html>......</html>
    

响应:

import requests
 
#allow_redirects=False#设置这个属性为False则是不允许重定向,反之可以重定向 
response = requests.get("http://www.baidu.com",allow_redirects=False)
#打印请求页面的状态(状态码)
print(type(response.status_code),response.status_code)
#打印请求网址的headers所有信息
print(type(response.headers),response.headers)
#打印请求网址的cookies信息
print(type(response.cookies),response.cookies)
#打印请求网址的地址
print(type(response.url),response.url)
#打印请求的历史记录(以列表的形式显示)
print(type(response.history),response.history)
属性或方法描述
response.status_code响应状态码
response.content把response对象转换成二进制数据
response.text把response对象转换成字符串数据
response.encoding定义response对象的编码
response.cookie获取请求后的cookie
response.url获取请求网址
response.json()内置的json解码器
response.headers以字典对象存储服务器响应头,字典不区分大小写

内置的状态码:

100: ('continue',),
101: ('switching_protocols',),
102: ('processing',),
103: ('checkpoint',),
122: ('uri_too_long', 'request_uri_too_long'),
200: ('ok', 'okay', 'all_ok', 'all_okay', 'all_good', '\\o/', '✓'),
201: ('created',),
202: ('accepted',),
203: ('non_authoritative_info', 'non_authoritative_information'),
204: ('no_content',),
205: ('reset_content', 'reset'),
206: ('partial_content', 'partial'),
207: ('multi_status', 'multiple_status', 'multi_stati', 'multiple_stati'),
208: ('already_reported',),
226: ('im_used',),

# Redirection.
300: ('multiple_choices',),
301: ('moved_permanently', 'moved', '\\o-'),
302: ('found',),
303: ('see_other', 'other'),
304: ('not_modified',),
305: ('use_proxy',),
306: ('switch_proxy',),
307: ('temporary_redirect', 'temporary_moved', 'temporary'),
308: ('permanent_redirect',
      'resume_incomplete', 'resume',), # These 2 to be removed in 3.0

# Client Error.
400: ('bad_request', 'bad'),
401: ('unauthorized',),
402: ('payment_required', 'payment'),
403: ('forbidden',),
404: ('not_found', '-o-'),
405: ('method_not_allowed', 'not_allowed'),
406: ('not_acceptable',),
407: ('proxy_authentication_required', 'proxy_auth', 'proxy_authentication'),
408: ('request_timeout', 'timeout'),
409: ('conflict',),
410: ('gone',),
411: ('length_required',),
412: ('precondition_failed', 'precondition'),
413: ('request_entity_too_large',),
414: ('request_uri_too_large',),
415: ('unsupported_media_type', 'unsupported_media', 'media_type'),
416: ('requested_range_not_satisfiable', 'requested_range', 'range_not_satisfiable'),
417: ('expectation_failed',),
418: ('im_a_teapot', 'teapot', 'i_am_a_teapot'),
421: ('misdirected_request',),
422: ('unprocessable_entity', 'unprocessable'),
423: ('locked',),
424: ('failed_dependency', 'dependency'),
425: ('unordered_collection', 'unordered'),
426: ('upgrade_required', 'upgrade'),
428: ('precondition_required', 'precondition'),
429: ('too_many_requests', 'too_many'),
431: ('header_fields_too_large', 'fields_too_large'),
444: ('no_response', 'none'),
449: ('retry_with', 'retry'),
450: ('blocked_by_windows_parental_controls', 'parental_controls'),
451: ('unavailable_for_legal_reasons', 'legal_reasons'),
499: ('client_closed_request',),

# Server Error.
500: ('internal_server_error', 'server_error', '/o\\', '✗'),
501: ('not_implemented',),
502: ('bad_gateway',),
503: ('service_unavailable', 'unavailable'),
504: ('gateway_timeout',),
505: ('http_version_not_supported', 'http_version'),
506: ('variant_also_negotiates',),
507: ('insufficient_storage',),
509: ('bandwidth_limit_exceeded', 'bandwidth'),
510: ('not_extended',),
511: ('network_authentication_required', 'network_auth', 'network_authentication'),

import requests
response = requests.get('http://www.jianshu.com/404.html')
# 使用request内置的字母判断状态码
 
#如果response返回的状态码是非正常的就返回404错误
if response.status_code != requests.codes.ok:
    print('404')
 
#如果页面返回的状态码是200,就打印下面的状态
response = requests.get('http://www.jianshu.com')
if response.status_code == 200:
    print('200')

request 高级操作

文件上传
import requests
url = "http://httpbin.org/post"
files= {"files":open("test.jpg","rb")}
response = requests.post(url,files=files)
print(response.text)

获取cookie

import requests
response = requests.get('https://www.baidu.com')
print(response.cookies)
for key,value in response.cookies.items():
    print(key,'==',value)

会话保持

cookie的一个作用就是可以用于模拟登录,做会话保持

import requests
session = requests.session()
session.get('http://httpbin.org/cookies/set/number/12456')
response = session.get('http://httpbin.org/cookies')
print(response.text)
cookie 和 session 区别
  • cookie数据存放在客户的浏览器上,session数据放在服务器上
  • cookie不是很安全,别人可以分析存放在本地的cookie并进行cookie欺骗
  • session会在一定时间内保存在服务器上。当访问增多,会比较占用你服务器的性能
  • 单个cookie保存的数据不能超过4K,很多浏览器都限制一个站点最多保存20个cookie
session发送请求后,实现登录后继续访问
import requests
url='https://www.xslou.com/login.php'
data={'username':'18600605736', 'password':'57365736', 'action':'login'}
 
# 使用session发送请求
session = requests.session()
resp=session.post(url,data=data)    # 使用session发送post请求
resp.encoding='gb2312'
# print( resp.text)        # <html>..<title>登录成功</title>....</html>
 
# 推荐小说      # 推荐成功的链接
hot_url='https://www.xslou.com/modules/article/uservote.php?id=71960'
resp2=session.get(hot_url)    # 使用session发送get请求
resp2.encoding='gb2312'
print(resp2.text)        # <html>..<title>处理成功</title>....</html>
SSL证书认证参数 verify
  • 参数值:True(默认)| False
  • 适用网站:https类型网站但是没有经过 证书认证机构 认证的网站
  • 适用场景:当程序中抛出SSLError异常则考虑使用此参数
  • 使用示例:requests.get(url=url,headers=headers,verify=False)
  • 当verify参数设置为False时,则不会再对网站进行SSL证书认证
设置超时时间 timeout

我们可以通过timeout属性设置超时时间,一旦超过这个时间还没获得响应内容,就会提示错误。

import requests
requests.get('http://github.com', timeout=0.001)
 
---------------------以下为输出结果(报错)---------------------
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)
代理IP参数 proxies
  • 语法格式:proxies = { ‘协议’:‘协议://IP:端口号’}

  • 示例:

    proxies = {
    	'http':'http://IP:端口号',
    	'https':'http://IP:端口号',
    }
    
  • 当我们抓取的地址为http时,则会选择proxies中http的代理,反之为https

import requests
 
url = 'http://httpbin.org/get'
headers = {'User-Agent':'Mozilla/5.0'}
# 定义代理,再代理IP网站中查找免费代理IP
proxies = {
    'http':'http://112.85.164.220:9999',
    'https':'https://112.85.164.220:9999'
}
html = requests.get(url=url,proxies=proxies,headers=headers,timeout=5).text
print(html)

*私密代理和独享代理*

  • 语法格式: proxies = {‘协议’:‘协议://用户名:密码@IP:端口号’}

  • 示例:

    proxies = {
    	'http':'http://用户名:密码@IP:端口号',
    	'https':'http://用户名:密码@IP:端口号',
    }
    
  • 当我们抓取的地址为http时,则会选择proxies中http的代理,反之为https

获取二进制数据

一般来说,对于非文本请求,可以以字节形式访问响应正文。

# 获取二进制数据
 
# 案例:保存百度图片
import requests
url='https://www.baidu.com/img/bd_logo1.png'
resp=requests.get(url)
# 存储
with open('logo.png','wb') as file:
    # resp.content:把response对象转换为二进制数据
    file.write(resp.content)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值