Requsets库的基本使用

14 篇文章 1 订阅

1. Requests库的7个主要方法

requests.request()
# 构造一个请求,支撑以下各方法的基础方法
 
requests.get()
# 获取HTML网页的主要方法,对应于HTTP的GET
 
requests.head()
# 获取HTML网页的头部信息,对应HTTP的HEAD
 
requests.post()
# 向HTML网页提交POST请求的方法,对应HTTP的POST
 
requests.put()
# 向HTML网页提交PUT请求的方法,对应于HTTP的PUT
 
requests.patch()
# 向HTML网页提交局部修改请求,对应于HTTP的PATCH
 
requests.delete()
# 向HTML页面提交删除请求,对应于HTTP的DELETE
r = requests.get("http://www.baidu.com")

Requests库的get()方法:
r=request.get(url)/构造向服务器请求资源的Request对象,同时返回一个包含服务器资源的Respose对象
r就是一个Respose对象,它包含了爬虫返回的全部内容, 也包含了我们向服务器请求的Resquset信息

2. Repose对象的属性

r.status_code
# HTTP请求的返回状态,状态码200连接成功,404表示连接失败或者就是非200就是失败的
# 以下执行的条件就是要是r.status_code=200的基础上才能够进行的
 
r.text
# HTTP响应内容的 字符串形式,即url对应的页面内容
 
r.encoding
# 从HTTP header中猜测的响应内容编码方式(并没有进行分析内容,只是一个猜测)
 
r.apparent_encoding
# 从内容分析出的响应内容编码方式(备选编码方式)
 
r.content
# HTTP相应内容的二进制形式
 
r.raise_for_status()
# 如果不是200,产生异常requests.HTTPError

示例:

# HTTP请求类型
# get类型
r = requests.get('https://github.com/timeline.json')
# post类型
r = requests.post("http://m.ctrip.com/post")
# put类型
r = requests.put("http://m.ctrip.com/put")
# delete类型
r = requests.delete("http://m.ctrip.com/delete")
# head类型
r = requests.head("http://m.ctrip.com/head")
# options类型
r = requests.options("http://m.ctrip.com/get")
 
# 获取响应内容
print(r.content) #以字节的方式去显示,中文显示为字符
print(r.text) #以文本的方式去显示
 
#URL传递参数
payload = {'keyword': '香港', 'salecityid': '2'}
r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) 
print(r.url) #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=香港
 
#获取/修改网页编码
r = requests.get('https://github.com/timeline.json')
print (r.encoding)
 
 
#json处理
r = requests.get('https://github.com/timeline.json')
print(r.json()# 需要先import json    
 
# 定制请求头
url = 'http://m.ctrip.com'
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
r = requests.post(url, headers=headers)
print (r.request.headers)
 
#复杂post请求
url = 'http://m.ctrip.com'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下
 
# post多部分编码文件
url = 'http://m.ctrip.com'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
 
# 响应状态码
r = requests.get('http://m.ctrip.com')
print(r.status_code)
    
# 响应头
r = requests.get('http://m.ctrip.com')
print (r.headers)
print (r.headers['Content-Type'])
print (r.headers.get('content-type')) #访问响应头部分内容的两种方式
    
# Cookies
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']    #读取cookies
    
url = 'http://m.ctrip.com/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies) #发送cookies
 
#设置超时时间
r = requests.get('http://m.ctrip.com', timeout=0.001)
 
#设置访问代理
proxies = {
           "http": "http://10.10.1.10:3128",
           "https": "http://10.10.1.100:4444",
          }
r = requests.get('http://m.ctrip.com', proxies=proxies)
 
 
#如果代理需要用户名和密码,则需要这样:
proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}

3. Requests库的异常

requests.ConnectionError
# 网络连接错误异常
 
requests.HTTPError
# HTTP错误异常
 
requests.URLRequired
# url缺失异常
 
requests.TooManyRedirects
# 超过最大重定向次数,产生重定向的异常
 
requests.ConnectTimeout
# 连接远程服务器超时异常(仅仅指那一个异常)
 
requests.Timeout
# 请求URL超时,产生超时异常(整个过程的超时异常)
# 通用代码框架
def GetHTMLText(url):
    try:
        r = requests.get(url)
        r.raise_for_status()
        # 最重要的一步,如果r.status_code!=200,他将先产生一次异常,能够被except进行捕获到
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "产生异常!!!"
import requests
 
URL = 'http://ip.taobao.com/service/getIpInfo.php'  # 淘宝IP地址库API
try:
    r = requests.get(URL, params={'ip': '8.8.8.8'}, timeout=1)
    r.raise_for_status()  # 如果响应状态码不是 200,就主动抛出异常
except requests.RequestException as e:
    print(e)
else:
    result = r.json()
    print(type(result), result, sep='\n')

4. HTTP协议

HTTP超文本传输协议:
是基于“请求与响应”模式的,无状态的应用层协议,采用URL作为定位网络资源的标志
URL的格式:http://host[:port][path]
host:合法的Internet主机域名或IP地址
port:端口号
path:请求资源的路径

HTTP协议对资源的操作:
GET:请求获取URL位置的资源
HEAD:请求获取URL位置资源的响应消息报告,即获得该资源的头部信息
POST:请求向URL位置的资源后附加新的数据
PUT:请求向URL位置存储一个资源覆盖原URL位置的资源
PATCH:请求局部更新URL位置的资源,即改变该处资源的部分内容
DELETE:请求删除URL位置存储的资源

5. requests库的七种方法:

5.1 requests.request()

可以说是最重要的方法,它可以用method参数通过传递’get’、‘options’、‘head’、‘put’、‘patch’、'delete’来替代后面六种方法。其实,后面的六种方法都是调用的requests.request()

 
requests.request(method,url,**kwargs)(**kwargs是13个访问控制参数)
method:GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS(使用较少)
 
 
# 例:r=requests.request('Get',url,**kwargs)
# **kwargs:控制访问的参数,均为可选项
 
params:字典或者字节序列,作为参数增加到url中,
# 通过这样一个参数,可以把一些键值对增加到url中使得url再去访问时不止访问的是这个资源,而同时带入了一些参数,服务器可以接受这些参数,并根据这些参数筛选部分资源,返回回来
 
data:字典、字典序列或文件对象,作为Request的内容
 
json:JSON格式的数据,作为Request的内容
 
headers:字典,HTTP定制头的相关域
 
cookies:字典或者CookieJar,Request中的cookie
 
auth:元组,支持HTTP认证功能
 
files:字典类型,传输文件
 
timeout:设置的超时时间,秒为单位
 
proxies:字典类型,设定访问代理服务器,可以增加登录认证,可有效防止对爬虫的逆追踪
 
allow_redirects:True/False,默认为True,重定向开关
 
stream:True/False,默认为True,获取内容立即下载开关
 
verify:True/False,默认为True,认证SSL证书的开关
 
cert:本地SSL证书路径
5.2 requests.get()
requests.get(url,params=None,**kwargs)
 
url:拟获取页面的url链接
 
params:url中的额外参数,字典或者字节流格式,可选
 
**kwargs:12个控制访问的参数
5.3 requests.head()
requests.head(url,**kwargs)
 
url:拟获取页面的url链接
 
**kwargs:13个控制访问的参数

Requests库的head()方法主要用于获取HTML网页头信息,相当于HTTP的HEAD。例如,抓取百度首页的头部信息,示例代码如下:

import requests
r = requests.head('http://www.baidu.com')
print(r.headers)
{‘Cache-Control’: ‘private, no-cache, no-store, proxy-revalidate, no-transform’, ‘Connection’: ‘keep-alive’, ‘Content-Encoding’: ‘gzip’, ‘Content-Type’: ‘text/html’, ‘Date’: ‘Sat, 18 Apr 2020 10:24:26 GMT’, ‘Last-Modified’: ‘Mon, 13 Jun 2016 02:50:05 GMT’, ‘Pragma’: ‘no-cache’, ‘Server’: ‘bfe/1.0.8.18}

request

5.4 requests.post()
requests.post(url,data=None,json=None,**kwargs)
 
url:拟获取页面的url链接
 
data:字典、字典序列或文件对象,作为Request的内容
 
json:JSON格式的数据,作为Request的内容
 
**kwargs:11个控制访问的参数
5.5 requests.put()
requests.put(url,data=None,**kwargs)
 
url:拟获取页面的url链接
 
data:字典、字典序列或文件对象,作为Request的内容
 
**kwarges:12个控制访问的参数
5.6 requests.patch()
requests.patch(url,data=None,**kwargs)
 
url:拟获取页面的url链接
 
data:字典、字典序列或文件对象,作为Request的内容
 
**kwarges:12个控制访问的参数
5.7 requests.delete()
requests.delete(url,**kwargs)
 
url:拟删除页面的url链接
 
**kwarges:13个控制访问的参数

Requests库的delete()方法主要用于向HTTP网页提交删除请求,相当于HTTP的DELETE。这里,我们给指定的url地址http://httpbin.org用delete()方法删除sendmsg信息,示例代码如下:

import requests
r = requests.delete('http://httpbin.org/delete')
print(r.text)

request
可以看出,form表单的内容为空,通过delete()方法我们成功将字典中的值删除成功。

6. 其他用法

  • json请求
#! /usr/bin/python3
import requests
import json
 
 
class url_request():
    def __init__(self):
        ''' init '''
 
if __name__ == '__main__':
    heard = {'Content-Type': 'application/json'}
    payload = {'CountryName': '中国',
               'ProvinceName': '四川省',
               'L1CityName': 'chengdu',
               'L2CityName': 'yibing',
               'TownName': '',
               'Longitude': '107.33393',
               'Latitude': '33.157131',
               'Language': 'CN'}
    r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity", heards=heard, data=payload)
    data = r.json()
    if r.status_code!=200:
        print('LBSLocateCity API Error' + str(r.status_code))
    print(data['CityEntities'][0]['CityID'])  # 打印返回json中的某个key的value
    print(data['ResponseStatus']['Ack'])
    print(json.dump(data, indent=4, sort_keys=True, ensure_ascii=False))  # 树形打印json,ensure_ascii必须设为False否则中文会显示为unicode
  • Xml请求
#! /usr/bin/python3
import requests
 
class url_request():
    def __init__(self):
        """init"""
 
if __name__ == '__main__':
    heards = {'Content-type': 'text/xml'}
    XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>'
    url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx'
    r = requests.post(url=url, heards=heards, data=XML)
    data = r.text
    print(data)
  • 上传文件

使用request模块,也可以上传文件,文件的类型会自动进行处理:

import requests
 
url = 'http://127.0.0.1:8080/upload'
files = {'file': open('/home/rxf/test.jpg', 'rb')}
#files = {'file': ('report.jpg', open('/home/lyb/sjzl.mpg', 'rb'))}     #显式的设置文件名
 
r = requests.post(url, files=files)
print(r.text)

request更加方便的是,可以把字符串当作文件进行上传:

import requests
 
url = 'http://127.0.0.1:8080/upload'
files = {'file': ('test.txt', b'Hello Requests.')}     #必需显式的设置文件名
 
r = requests.post(url, files=files)
print(r.text)
  • 基本身份认证(HTTP Basic Auth)
import requests
from requests.auth import HTTPBasicAuth
 
r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=HTTPBasicAuth('user', 'passwd'))
# r = requests.get('https://httpbin.org/hidden-basic-auth/user/passwd', auth=('user', 'passwd'))    # 简写
print(r.json())
  • 摘要式身份认证
    另一种非常流行的HTTP身份认证形式是摘要式身份认证,Requests对它的支持也是开箱即可用的:
requests.get(URL, auth=HTTPDigestAuth('user', 'pass'))
  • Cookies与会话对象

如果某个响应中包含一些Cookie,你可以快速访问它们:

import requests
 
r = requests.get('http://www.google.com.hk/')
print(r.cookies['NID'])
print(tuple(r.cookies))

要想发送你的cookies到服务器,可以使用 cookies 参数:

import requests
 
url = 'http://httpbin.org/cookies'
cookies = {'testCookies_1': 'Hello_Python3', 'testCookies_2': 'Hello_Requests'}
# 在Cookie Version 0中规定空格、方括号、圆括号、等于号、逗号、双引号、斜杠、问号、@,冒号,分号等特殊符号都不能作为Cookie的内容。
r = requests.get(url, cookies=cookies)
print(r.json())

会话对象让你能够跨请求保持某些参数,最方便的是在同一个Session实例发出的所有请求之间保持cookies,且这些都是自动处理的,甚是方便。

import requests
 
headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
           'Accept-Encoding': 'gzip, deflate, compress',
           'Accept-Language': 'en-us;q=0.5,en;q=0.3',
           'Cache-Control': 'max-age=0',
           'Connection': 'keep-alive',
           'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}
 
s = requests.Session()
s.headers.update(headers)
# s.auth = ('superuser', '123')
s.get('https://www.kuaipan.cn/account_login.htm')
 
_URL = 'http://www.kuaipan.cn/index.php'
s.post(_URL, params={'ac':'account', 'op':'login'},
       data={'username':'****@foxmail.com', 'userpwd':'********', 'isajax':'yes'})
r = s.get(_URL, params={'ac':'zone', 'op':'taskdetail'})
print(r.json())
s.get(_URL, params={'ac':'common', 'op':'usersign'})
  • 失败重试
    默认requests请求失败后不会重试,但是我们跑case时难免遇到一些网络,服务重启,外部原因导致case失败,我们可以在Session实例上附加HTTPAdapaters 参数,增加失败重试次数。
request_retry = requests.adapatrs.HTTPAdapaters(max_retries=3)
 
self.session.mount('https://',request_retry)  
self.session.mount('http://',request_retry)
  • requests使用连接池
import requests

session = requests.Session()
session.mount('http://', requests.adapters.HTTPAdapter(pool_connections=1, pool_maxsize=20, max_retries=3))

session.get("http://lr.cool")

其中涉及到的几个参数:
pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE,
max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK

"""
:param pool_connections: The number of urllib3 connection pools to cache.
:param pool_maxsize: The maximum number of connections to save in the pool.
:param max_retries: The maximum number of retries each connection
        should attempt. Note, this applies only to failed DNS lookups, socket
        connections and connection timeouts, never to requests where data has
        made it to the server. By default, Requests does not retry failed
        connections. If you need granular control over the conditions under
        which we retry a request, import urllib3's ``Retry`` class and pass
        that instead.
:param pool_block: Whether the connection pool should block for connections.
"""
# 默认值
DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0

(1)一个host对应一个连接池,默认一个连接池同时支持10个链接,当超过限制时,由pool_block参数决定是否阻塞等待。

(2)也可以通Sessio的mount函数和HTTPAdapter修改默认配置。

  • 其他
1:保持请求之间的Cookies,我们可以这样做。
 
import requests
self.session = requests.Session()
self.session.get(login_url) # 可以保持登录态
 
2:请求时,会加上headers,一般我们会写成这样
 
self.session.get(url, params, headers=headers)
 
唯一不便的是之后的代码每次都需要这么写,代码显得臃肿,所以我们可以这样:
 
#在构造函数中,这样设置是全局的。
 
# 设置请求头
self.s = requests.Session()
self.s.headers = {'balabala'}
 
# 移除服务器验证
self.s.verify = False
 
# 设置代理
self.s.proxies={'aa'}
 
# 如果后续headers有改变,再次赋值就可以了。
self.s.get(url, params, headers=new_headers)

7. 相关文章

python 爬虫之requests高级用法
https://www.cnblogs.com/xingxingnbsp/p/12395275.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值