python3.6通过urllib模块使用post/get方法

1. 通过使用urllib模块使用post/get方式请求url;

2. urllib模块使用过程中的异常处理。


import  urllib.request
import  urllib.parse
import  urllib.error #url异常处理

###GET方法
keywd="python"
keywd=urllib.request.quote(keywd)  #搜索中文的方法
url = "http://www.baidu.com/s?wd="+keywd
req=urllib.request.Request(url)
data=urllib.request.urlopen(req).read()
print(data.decode('utf-8','ignore')) #转为utf-8,如果出现异常,责忽略
fh=open("/Users/huangliao/Desktop/1.html","wb")
fh.write(data)
fh.close();


####post
keywd="python"
keywd=urllib.request.quote(keywd)
url="http://www.baidu.com/s"
mydata=urllib.parse.urlencode({"wd":"python"}).encode('utf-8')
req=urllib.request.Request(url,mydata)
data=urllib.request.urlopen(req).read().decode("utf-8")
print(data)

'''
在清求url请求时会发现存在异常情况,常用的请求异常类是  HTTPError/URLError 两种,
HTTPError异常时URLError异常的子类,是带异常状态码和异常原因的,而URLError异常类
是不带状态码的,所以在使用中不用直接用URLError代替HTTPError异常,如果要代替,一定
要判断是否有状态码属性
URLError:
1/连接不上远程服务器;
2/url不存在;
3/本地没有网络;
4/假如触发httperror

所以通常用特殊处理来使用URLError来替代HTTPError异常

'''

try:
    urllib.request.urlopen("http://www.blog.csdn.net")
except urllib.error.URLError as e:
    if hasattr(e,"code"):
        print("code:")
        print(e.code)
    if hasattr(e,"reason"):
        print("reason:")
        print(e.reason)
finally:
    print("URLError ")





你可能感兴趣的:(Python)