关于urllib库

几个模块

data参数,如果加的话即为post请求,不加就是get请求

 1 # 对于urllib的使用
 2 # 1.get请求
 3 import urllib.request  # url请求模块
 4 response = urllib.request.urlopen('http://www.baidu.com')
 5 print(response.read().decode('utf-8'))
 6 # response.read()是一个bytes类型的数据,所以需要调用decode设置编码格式,使其变成字符串
 7 
 8 # 2.post请求
 9 # post请求需要传入data参数,data为bytes类型,所以encode编码
10 import urllib.parse  # url解析模块
11 data = bytes(urllib.parse.urlencode({'word': 'hello'}),encoding ='utf8')
12 response = urllib.request.urlopen('http://httpbin.org/post', data=data)
13 print(response.read())
14 # timeout 参数  即在规定的时间内没有得到响应的话,就会抛出异常
15 import urllib.error  # 异常处理模块
16 import socket
17 try:
18     response = urllib.request.urlopen('http://httpbin.org/get', timeout=0.1)
19 except urllib.error.URLError as e:
20     if isinstance(e.reason, socket.timeout):
21         # e.reason 错误的原因是timeout类型
22         print('Time out')
23 
24 # 3.如果要加入更多的参数,像headers之类的,操作过程
25 # Request
26 request = urllib.request.Request('http://python.org') # 构建一个request对象
27 response = urllib.request.urlopen(request)
28 print(response.read().decode('utf-8'))
29 # ctrl+c 终止程序
30 from urllib import request, parse
31 # 实际上,将要传入的参数作为一个整体传入即可
32 url = 'http://httpbin.org/post'
33 headers = {
34     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
35                  'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
36     'Host': 'httpbin.org'
37 }
38 
39 dict = {
40     'name': 'Gemy'
41 }
42 
43 data = bytes(parse.urlencode(dict).encode('utf8'))
44 req = request.Request(url=url, data=data, headers=headers, method='POST')
45 response = request.urlopen(req)
46 print(response.read().decode('utf8'))
47 
48 # Handler
49 # cookies
50 #   比较麻烦。相比于request模块

 request模块比较人性化,,,还是用它好,下一章详细理解request模块

 

https://docs.python.org/3/library/urllib.html

官方文档,有兴趣可以深究。。

posted on 2018-01-06 17:38  java小萌新(づ ̄3 ̄)  阅读(219)  评论(0编辑  收藏  举报

导航