03、urllib库的使用

1、什么是urllib?

urllib的4个模块

urllib是python内置的http请求库,主要有4个模块,分别是:urllib.request(请求模块)、urllib.error(异常处理模块)、urlib.parse(url解析模块)、urllib.robotparser(robots.txt解析模块)

相对Python2的变化

2、urllib用法讲解之urllib.request

urlopen方法使用

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')

print(response.read().decode('utf-8'))

urlopen()的第一个参数

import urllib.parse

import urllib.request

data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf-8')

response = urllib.request.urlopen('http://httpbin.org/post', data=data)

print(response.read())

urlopen()的第二个参数

import urllib.request

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

print(response.read())

urlopen()的第三个参数

#演示urllib.error

import socket

import urllib.request

import urllib.error

try:

    response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)

except urllib.error.URLError as e:

    if isinstance(e.reason, socket.timeout):

        print('TIME OUT')

urllib.error演示

2、response响应

response响应

#演示响应类型

import urllib.request

response = urllib.request.urlopen('http://www.python.org')

print(type(response))

演示响应

#演示状态头、响应头

import urllib.request

response = urllib.request.urlopen('http://www.python.org')

print(response.status)

print(response.getheaders())

print(response.getheader('server'))


演示状态码、响应头

3、request

request

#演示request

import urllib.request

request = urllib.request.Request('http://www.python.org')

response = urllib.request.urlopen(request)

print(response.read().decode('utf-8'))

演示request

4、handler

handler
cookie

urllib用法讲解之urllib.error

异常处理

urllib用法讲解之urllib.urlparse

urlparse
urlunparse
urljoin
urlencode

官方文档参考地址:https://docs.python.org/zh-cn/3/library/urllib.html

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。