接口常用三方请求模块urllib,requests

客户端HTTP请求

统一资源定位符

URL(Uniform / Universal Resource Locator的缩写)

定义:统一资源定位符,是用于完整地描述Internet上网页和其他资源的地址的一种标识方法。

基本格式:scheme://host[:port#]/path/…/[?query-string][#anchor]

scheme:协议(例如:http, https, ftp)
host:服务器的IP地址或者域名
port#:服务器的端口(如果是走协议默认端口,缺省端口80)
path:访问资源的路径
query-string:参数,发送给http服务器的数据
anchor:锚(跳转到网页的指定锚点位置)

常用请求报头

Host: www.baidu.com
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 	(KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh,zh-CN;q=0.8,ar;q=0.6,zh-TW;q=0.4
Cookie: BAIDUID=AE4D1DA6B2D6689BB8C557B3436893E3:FG=1; 	BIDUPSID=AE4D1DA6B2D6689BB8C557B3436893E3; PSTM=1501466227; 			BD_UPN=12314353; BD_CK_SAM=1; PSINO=1; 	H_PS_PSSID=1420_25548_21080_20929; 	BDORZ=B490B5EBF6F3CD402E515D22BCDA1598; BDSVRTM=0

请求方法

序号方法描述
1GET请求指定的页面信息,并返回实体主体。
2HEAD类似于get请求,只不过返回的响应中没有具体的内容,用于获取报头
3POST向指定资源提交数据进行处理请求(例如提交表单或者上传文件),数据被包含在请求体中。POST请求可能会导致新的资源的建立和/或已有资源的修改。
4PUT从客户端向服务器传送的数据取代指定的文档的内容。
5DELETE请求服务器删除指定的页面。
6CONNECTHTTP/1.1协议中预留给能够将连接改为管道方式的代理服务器。
7OPTIONS允许客户端查看服务器的性能。
8TRACE回显服务器收到的请求,主要用于测试或诊断。

HTTP响应状态码

下面是常见的HTTP状态码:

  • 200 - 请求成功
  • 301 - 资源(网页等)被永久转移到其它URL
  • 404 - 请求的资源(网页等)不存在
  • 500 - 内部服务器错误
  • xxx…

urllib模块请求篇

Urllib是python内置的HTTP请求库,urllib提供了一系列用于操作URL的功能。

urlopen

关于urllib.request.urlopen参数的介绍:
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

urlopen参数的使用

先写一个简单的例子:

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
urlopen一般常用的有三个参数,它的参数如下:
urllib.requeset.urlopen(url,data,timeout)
response.read() #可以获取到网页的内容

通过输出结果可以发现它是一个 HTTPResposne 类型的对象,它主要包含的方	法有 read()、readinto()、getheader(name)、getheaders()、fileno() 等方法和 	msg、version、status、reason、debuglevel、closed 等属性。

调用 status 属性就可以得到返回结果的状态码,如 200 代表请求成功,404 代表网页未找到等。

data参数
data 参数是可选的,如果要添加 data,它要是字节流编码格式的内容,即 bytes 类型,通过 bytes() 方法可以进行转化,另外如果传递了这个 data 参数,它的请求方式就不再是 GET 方式请求,而是 POST。

需要用 urllib.parse 模块里的 urlencode() 方法来将参数字典转化为字符串。第二个参数指定编码格式,在这里指定为 utf8。
import urllib.parse
import urllib.request

data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())
timeout参数
timeout 参数可以设置超时时间,单位为秒,意思就是如果请求超出了设置的这个时间还没有得到响应,就会抛出异常,如果不指定,就会使用全局默认时间。它支持 HTTP、HTTPS、FTP 请求。

Request

下面我们看一下 Request 都可以通过怎样的参数来构造,它的构造方法如下:

urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)

首先我们用一个实例来感受一下 Request 的用法:

from urllib import request, parse

url = 'http://httpbin.org/post'
headers = {
    'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)',
    'Host': 'httpbin.org'
}
dict = {
    'name': 'zhaofan'
}
data = bytes(parse.urlencode(dict), encoding='utf8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))
在这里我们通过四个参数构造了一个 Request,url 即请求 URL,在headers 中指定了 User-Agent 和 Host,传递的参数 data 用了 urlencode() 和 bytes() 方法来转成字节流,另外指定了请求方式为 POST。

通过观察结果可以发现,我们成功设置了 data,headers 以及 method。
另外 headers 也可以用 add_header() 方法来添加。

req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')

处理异常

在很多时候我们通过程序访问页面的时候,有的页面可能会出现错误,类似404,500等错误

这里我们需要知道的是在urllb异常这里有两个个异常错误:
URLError,HTTPError,HTTPError是URLError的子类

URLError里只有一个属性:reason,即抓异常的时候只能打印错误信息

HTTPError里有三个属性:code,reason,headers,即抓异常的时候可以获得code,reson,headers三个信息,例子如下:
from urllib import request,error
try:
    response = request.urlopen("http://pythonsite.com/1111.html")
except error.HTTPError as e:
    print(e.reason)
    print(e.code)
    print(e.headers)
except error.URLError as e:
    print(e.reason)

else:
    print("reqeust successfully")

URL解析

urlparse

这里就是可以对你传入的url地址进行拆分
同时我们是可以指定协议类型:

result = urlparse("www.baidu.com/index.html;user?		id=5#comment",scheme="https")

图片

这样拆分的时候协议类型部分就会是你指定的部分,当然如果你的url里面已经带了协议,你再通过scheme指定的协议就不会生效

urlunpars

其实功能和urlparse的功能相反,它是用于拼接,例子如下:

from urllib.parse import urlunparse

data = ['http','www.baidu.com','index.html','user','a=123','commit']
print(urlunparse(data))

urlencode

这个方法可以将字典转换为url参数,例子如下
from urllib.parse import urlencode

params = {
    "name":"zhaofan",
    "age":23,
}
base_url = "http://www.baidu.com?"

url = base_url+urlencode(params)
print(url)
输出结果:http://www.baidu.com?name=zhaofan&age=23

quote/quote_plus

>>> from urllib import parse
>>> parse.quote('a&b/c')  #未编码斜线
'a%26b/c'
>>> parse.quote_plus('a&b/c')  #编码了斜线
'a%26b%2Fc'

unquote/unquote_plus

from urllib import parse
>>> parse.unquote('1+2')  #不解码加号
'1+2'
>>> parse.unquote_plus('1+2')  #把加号解码为空格
'1 2'

opener

urllib2.urlopen()函数不支持验证、cookie或者其它HTTP高级功能。要支持这些功能,必须使用build_opener()函数创建自定义Opener对象。

参数handler是Handler实例,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。

  1. 密码验证(HTTPBasicAuthHandler)
    HTTPBasicAuthHandler()处理程序可用add_password()来设置密码。
    h.add_password(realm,uri,user,passwd)
    realm是与验证相关联的名称或描述信息,取决于远程服务器。uri是基URL。user和passwd分别指定用户名和密码。
import urllib.request
auth=urllib.request.HTTPBasicAuthHandler() 
auth.add_password('Administrator','http://www.example.com','Dave','123456') 
opener=urllib.request.build_opener(auth) 
u=opener.open('http://www.example.com/evilplan.html') 
  1. Cookie处理(HTTPCookieProcessor)
import http.cookiejar, urllib.request
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name+"="+item.value)
  1. 代理(ProxyHandler)
    ProxyHandler(proxies)参数proxies是一个字典,将协议名称(http,ftp)等映射到相应代理服务器的URL。
proxy=ProxyHandler({'http':'http://someproxy.com:8080'}) 
auth=HTTPBasicAuthHandler() 
auth.add_password() 
opener=build_opener(auth,proxy) 

requests请求篇

安装:直接pip install requests

requests使用的是urllib3,它继承了urllib2的所有特性。requests有很大功能特性

  • 支持HTTP连接保持和连接池;
  • 支持使用cookie保持会话;
  • 支持文件上传;
  • 支持自动确定响应内容的编码;
  • 支持国际化的URL和POST数据自动编码。

请求示例

get 请求

import requests

kw = {'wd':'python'}
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}

# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("http://www.baidu.com/s?", params = kw, headers = headers)
print (response.text)
# 查看响应内容,response.content返回的字节流数据
print (response.content)
print (response.url)
# # 查看响应头部字符编码
print (response.encoding)
print (response.status_code)

post 请求

import requests

dict = {
    'name': 'zhaofan'
}
res = requests.request(method='post', url='http://httpbin.org/post', data=dict)
print(res.json())

requests.post方法中data与json参数区别

在通过requests.post()进行POST请求时,传入报文的参数有两个,一个是data,一个是json。

:data: (optional) Dictionary, list of tuples, bytes, or file-like
    object to send in the body of the :class:`Request`.
:json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.

data与json区别:

  1. 不管json是str还是dict,如果不指定headers中的content-type,默认为application/json

  2. data为dict时,如果不指定content-type,默认为application/x-www-form-urlencoded,相当于普通form表单提交的形式

  3. data为str时,如果不指定content-type,默认为text/plain

  4. json时,如果不指定content-type,默认为application/json

  5. 用data参数提交数据时,request.body的内容则为a=1&b=2的这种形式,用json参数提交数据时,request.body的内容则为’{“a”: 1, “b”: 2}'的这种形式

身份认证

许多要求身份认证的web服务都接受 HTTP Basic Auth。这是最简单的一种身份认证,并且 Requests 对这种认证方式的支持是直接开箱即可用。

以 HTTP Basic Auth 发送请求非常简单:

>>> from requests.auth import HTTPBasicAuth
>>> requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
<Response [200]>

事实上,HTTP Basic Auth 如此常见,Requests 就提供了一种简写的使用方式:

>>> requests.get('https://api.github.com/user', auth=('user', 'pass'))
<Response [200]>

像这样在一个元组中提供认证信息与前一个 HTTPBasicAuth 例子是完全相同的。

代理

如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求:

import requests

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}

requests.get("http://example.org", proxies=proxies)

若你的代理需要使用HTTP Basic Auth,可以使用 http://user:password@host/ 语法:

proxies = {
    "http": "http://user:pass@10.10.1.10:3128/",
}

cookie

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')

>>> r = requests.get(url, cookies=cookies)
>>> r.text
>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)

>>> r.cookies['example_cookie_name']
'example_cookie_value'

定制动词

有时候你会碰到一些服务器,处于某些原因,它们允许或者要求用户使用上述 HTTP 动词之外的定制动词。比如说 WEBDAV 服务器会要求你使用 MKCOL 方法。别担心,Requests 一样可以搞定它们。你可以使用内建的 .request 方法,例如:

>>> r = requests.request('MKCOL', url, data=data)
>>> r.status_code
200 # Assuming your call was correct

关于requests更详细的介绍,请参阅
https://docs.python-requests.org/zh_CN/latest/

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值