码迷,mamicode.com
首页 > Web开发 > 详细

urllib

时间:2019-02-22 12:13:27      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:span   context   关于   www.   sch   gen   err   ble   int   

什么是urllib

Urllib是python内置的HTTP请求库
包括以下模块
urllib.request 请求模块
urllib.error 异常处理模块
urllib.parse url解析模块
urllib.robotparser robots.txt解析模块

 

urlopen

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

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()可以获取到网页的内容,如果没有read(),将返回如下内容

data参数的使用

上述的例子是通过请求百度的get请求获得百度,下面使用urllib的post请求

import urllib.parse
import urllib.request

data=bytes(urllib.parse.urlencode({word:hello}),encoding=utf8)
print(data)
response=urllib.request.urlopen(http://httpbin.org/post,data=data)
html=response.read()
print(html)

  这里就用到urllib.parse,通过bytes(urllib.parse.urlencode())可以将post数据进行转换放到urllib.request.urlopen的data参数中。这样就完成了一次post请求。
所以如果我们添加data参数的时候就是以post请求方式请求,如果没有data参数就是get请求方式

  关于get和post:在客户机和服务机之间进行请求-响应时,两种最常被用到的方法是:get和post。

    get  从指定资源请求数据

    post  向指定的资源提交要被处理的数据

      技术图片

 

timeout参数的使用

在某些网络情况不好或者服务器端异常的情况会出现请求慢的情况,或者请求异常,所以这个时候我们需要给
请求设置一个超时时间,而不是让程序一直在等待结果。例子如下:

import urllib.request

response = urllib.request.urlopen(http://httpbin.org/get, timeout=1)
print(response.read())

运行之后我们看到可以正常的返回结果,接着我们将timeout时间设置为0.1
运行程序会提示错误socket.timeout:timed out 异常

对异常进行捕获

import urllib.request
import socket
import urllib.error

try:
    response = urllib.request.urlopen(http://httpbin.org/get, timeout=1)
    print(response.read())
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print(time out)

 

  

request

设置Headers

有很多网站为了防止程序爬虫爬网站造成网站瘫痪,会需要携带一些headers头部信息才能访问,最长见的有user-agent参数

写一个简单的例子:

import urllib.request

request = urllib.request.Request(https://python.org)
response = urllib.request.urlopen(request)
print(response.read().decode(utf-8))

给请求添加头部信息,从而定制自己请求网站是时的头部信息

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))

添加请求头的第二种方式

from urllib import request, parse

url = http://httpbin.org/post
dict = {
    name: Germey
}
data = bytes(parse.urlencode(dict), encoding=utf8)
req = request.Request(url=url, data=data, method=POST)
req.add_header(User-Agent, Mozilla/4.0 (compatible; MSIE 5.5; Windows NT))
response = request.urlopen(req)
print(response.read().decode(utf-8))

这种添加方式有个好处是自己可以定义一个请求头字典,然后循环进行添加

 

URL解析

urlparse

from urllib.parse import urlparse

result = urlparse("http://www.baidu.com/index.html;user?id=5#comment")
print(result)

技术图片

这里就是可以对你传入的url地址进行拆分
同时我们是可以指定协议类型:
result = urlparse("www.baidu.com/index.html;user?id=5#comment",scheme="https")
这样拆分的时候协议类型部分就会是你指定的部分,当然如果你的url里面已经带了协议,你再通过scheme指定的协议就不会生效

 

urllib

标签:span   context   关于   www.   sch   gen   err   ble   int   

原文地址:https://www.cnblogs.com/start20180703/p/10417460.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!