[关闭]
@myles 2019-01-12T00:01:52.000000Z 字数 1686 阅读 607

urllib 库学习笔记

未分类


urllib 库

1、urllib 库模块分类

2、urlopen() 函数

通过urlib.request.urlopen()函数方法来构建http请求

  1. urllib.request.urlopen(url, data=None, [timeout,] cafile=None, capath=None, cadefault=False, context=None)

(1)参数1: url

  1. from urllib import request
  2. url = 'http://httpbin.org/get'
  3. response = request.urlopen(url)
  4. print(response.read().decode('utf-8'))

(2)参数2:data

  1. from urllib import parse,request
  2. url = 'http://httpbin.org/post'
  3. form_data = {'key':'value'}
  4. data = bytes(parse.urlencode(form_data),encoding='utf-8')
  5. response = request.urlopen(url,data)
  6. response_text = response.read().decode('utf-8')
  7. print(response_text)

(3)参数3:timeout

  1. from urllib import request
  2. url = 'http://httpbin.org/get'
  3. response = request.urlopen(url, timeout = 1)
  4. print(response.read().decode('utf-8'))
  1. from urllib import request, error
  2. import socket
  3. url = 'http://httpbin.org/get'
  4. try:
  5. response = request.urlopen(url, timeout = 0.1)
  6. except error.URLError as e:
  7. if isinstance(e.reason, socket.timeout):
  8. print("Time Out ...")

3、response 响应类

(1)响应类型

  1. from urllib import request
  2. url = 'http://httpbin.org/get'
  3. response = request.urlopen(url)
  4. print(type(response))
<class 'http.client.HTTPResponse'>

(2)状态码、响应头

  1. from urllib import request
  2. url = 'http://httpbin.org/get'
  3. response = request.urlopen(url)
  4. print(response.status)
  5. print(response.getheaders())
  6. #print(response.getheaders['Server'])
200
[('Connection', 'close'), ('Server', 'gunicorn/19.9.0'), ('Date', 'Fri, 11 Jan 2019 15:30:00 GMT'), ('Content-Type', 'application/json'), ('Content-Length', '233'), ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Credentials', 'true'), ('Via', '1.1 vegur')]

(3)响应实体内容

  1. from urllib import request
  2. url = 'http://httpbin.org/ip'
  3. response = request.urlopen(url)
  4. print(response.read().decode('utf-8'))
{
  "origin": "60.166.83.51"
}

4、 urllib.request.Request() 类

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注