urllib库基础用法

(一)urlopen

import urllib.request

# 获取百度首页源代码
response = urllib.request.urlopen('http://wwww.baidu.com')
print(response.read().decode('utf-8'))

它是一个HTTPResponse类型的对象,主要包含read()、readinto()、getheader(name)/getheaders()/fileno()等方法,msg、version、status、reason、debuglevel、closed等属性

# 输出相应的状态码
print(response.status)
# 输出相应的头信息
print(response.getheaders())
# 通过调用getheader()方法,传递参数Server获取了响应头中的Server值
print(response.getheader('Server'))

urlopen()函数的API:
urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capatj=None,cadefault=False,context=None)

  • data参数
    附加数据。它是字节流编码格式的内容,即bytes类型
    需要通过bytes()方法转化。如果传递了此参数,请求方式非GET,而是POST方式。
# 转字节流采用bytes()方法,其第一个参数需是字符串类型。
# urlencode()方法(在urllib.parse模块里)可将参数字典转化成字符串,第二个参数指定编码格式。
import urllib.parse
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())
image.png

我们传递的参数data出现在form字段中,以POST方式传输数据

  • timeout 参数
    设置超时时间,单位为

通过设置超时时间来控制网页长时间未响应,跳过抓取,搭配try except语句来实现

import socket
import urllib.error

try:
    response = urllib.request.urlopen('https://www.baidu.com/',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('time out')

输出time out,因为0.1秒内目前不可能得到服务器响应

  • 其他参数
    context参数:必须是ssl.SSLContext类型,用来指定SSL设置
    cafile与capath参数:指定CA证书和它的路径,在请求HTTPS链接时有用
    cadefault参数:现已弃用,默认值为False

(二)Request

如果在请求中需加入headers等信息,需有request类来构建

import urllib.request

# 构造Request类型的对象数据结构
request = urllib.request.Request('https://python.org')
# 将对象传入urlopen()方法的参数中
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

可将请求独立成一个对象,且更丰富和灵活地配置参数

Request 的构造方法
class urllib.request.Request(url,data=None,headers={},origin_req_host=None,unverifiable=False,method=None)

  • data 参数
    需传bytes(字节流)类型的。若是字典,用urllib.parse模块里的urlencode()编码

  • headers 参数
    字典形式
    可直接构造或通过调用实例的add_header()方法添加

  • unverfiable 参数
    表示这个请求是否是无法验证,默认False,意思为用户没有足够权限来选择接收这个请求结果。
    例:请求一个HTML文档中的图片,但没有自动抓取图片的权限,这时unverfiable 的值为True

  • mothod 参数
    字符串
    用来指示请求使用的方法。比如get、post、put等。

from urllib import request,parse 

url = 'http://httpbin.org/post' 
headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE S. S; Windows NT)',
        'Host':'httpbin.org'}
dict = {'name':'sanmi'}
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'))

通过4个参数构造请求,输出如下

image.png

成功设置了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 S. S; Windows NT)') 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。