13-Python网络请求

1.常见请求体类型

    ①、Application/x-www-form-urlencoded:常见的POST数据提交方式;浏览器原生的from表单,如果不设置content-type属性,那么最终就会以Application/x-www-form-urlencoded方式提交数据

    ②、multipart/form-data:常见的 POST 数据提交的方式;我们使用表单上传文件时,必须让 form 的 Content-Type 等于这个值

    ③、application/json:用来告诉服务端消息主体是序列化后的 JSON 字符串

    ④、text/xml:它是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范

2.请求相关模块

import urllib.request
import http.cookiejar
import socket
import ssl
import random

print('urllib : ',dir(urllib))
print('urllib.request : ',repr(dir(urllib.request)))
print('http : ',dir(http))
print('http.cookiejar : ',dir(http.cookiejar))

3.构造Opener请求

    ①、默认Openers正常状况的Handles:ProxyHandler、UnknownHandler、HTTPHandler、HTTPDefaultErrorHandler、HTTPRedirectHandler、FTPHandler、 FileHandler、HTTPErrorProcessor

    ②、参数handler是Handler实例,常用的有HTTPBasicAuthHandler、HTTPCookieProcessor、ProxyHandler等。
    ③、build_opener ()返回的对象具有open()方法,与urlopen()函数的功能相同。

    ④、Cookie的关系:CookieJar --派生--> FileCookieJar  --派生--> MozillaCookieJar和LWPCookieJar

class zRequest(object):

    def __init__(self):
        # 设置超时时间
        socket.setdefaulttimeout(20)

    def openUrl(self,url,data=None):
        # 设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
        cj = http.cookiejar.LWPCookieJar()
        cookie_support = urllib.request.HTTPCookieProcessor(cj)
        # 请求代理
        proxy_support = urllib.request.ProxyHandler({'http': 'http://www.baidu.com'})
        # 关闭Https证书验证
        https_support = urllib.request.HTTPSHandler(context=ssl._create_unverified_context())
        # build_opener ()返回的对象具有open()方法,与urlopen()函数的功能相同
        opener = urllib.request.build_opener(cookie_support,proxy_support,https_support,urllib.request.HTTPHandler)
        # 请求头配置
        opener.addheaders = zRequest.getHeaders().items()
        # 安装opener
        urllib.request.install_opener(opener)
        # 开始请求
        try:
            response = opener.open(url,data)
        except Exception as e:
            print('请求错误:%s'%(repr(e)))
            raise Exception
        else:
            return response

    @staticmethod
    def getHeaders():
        # 请求头配置
        user_agents = ['Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
                       'Opera/9.25 (Windows NT 5.1; U; en)',
                       'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
                       'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
                       'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
                       'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
                       "Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7",
                       "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 "]
        choose_agent = random.choice(user_agents)
        # referer:从哪个站点链接过来的
        return {"User-agent":choose_agent,"Accept":"*/*",'Referer':'http://www.baidu.com'}

4.构造Request请求

request1 = urllib.request.Request('https://my.oschina.net/CoderW/blog',headers=zRequest.getHeaders())
print('Request1报头:',request1.headers)
# ssl创建一个未经验证的上下文(https)
context = ssl._create_unverified_context()
# 开始请求
# 请求参数:data=None,timeout=socket._GLOBAL_DEFAULT_TIMEOUT,cafile=None,capath=None,cadefault=False,context=None
response1 = urllib.request.urlopen(request1,context=context)
print('info:',response.info())
print('reason:',response.reason)
print('status:',response.status)
print('date info:',response.getheader('date'))
print(response1.read().decode('utf-8'))

5.常见错误

    ①、禁止访问403错误,请求被拒:urllib.error.HTTPError: HTTP Error 403: Forbidden
          缘由:很大可能是由于报头信息被拒

    ②、SLL证书验证错误:<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed
          缘由:访问https未关闭证书验证

转载于:https://my.oschina.net/CoderW/blog/997721

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值