Python2和Python3提交Get和Post请求及异常处理(try except)

本文主要介绍Python中,Python2和Python3发送提交Get和Post请求的方法及示例代码,包括请求中出现异常的处理(try except)。

1、Python2中Get和Post请求

1)Get请求

#coding=utf-8
import urllib
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf8')
word = urllib.urlencode({"wd":"cjavapy"})
url = 'http://www.baidu.com/s' + '?' + word
try:
    request = urllib2.Request(url)
    ##windows中cmd中乱码,可以使用.encode("gbk","ignore")试试
    print urllib2.urlopen(request).read().decode('utf-8')
except Exception,e:
    print(e)

2)Post请求

#coding=utf-8
import urllib
import urllib2
import sys
reload(sys)
sys.setdefaultencoding('utf8')
formdata = {
'name':'cjavapy'
}
data = urllib.urlencode(formdata)
try:
request = urllib2.Request(url = "http://httpbin.org/post", data=data)
response = urllib2.urlopen(request)
print response.read()
except Exception,e:
print(e)

2、Python3中Get和Post请求

1)Get请求

import urllib.request
import urllib.parse
data = urllib.parse.urlencode({'wd':'cjavapy'})
url  = 'http://wwww.baidu.com/s?' + data
# url = 'http://www.baidu.com/s?wd=' + urllib.parse.quote('cjavapy')
try:
    response = urllib.request.urlopen(url)
    print (response.read().decode('utf-8'))
except Exception as e:
    print(e)

2)Post请求

import urllib.request
import urllib.parse
data = bytes(urllib.parse.urlencode({'name':'cjavapy'}),encoding='utf8')
# url = 'http://www.baidu.com/s?wd=' + urllib.parse.quote('cjavapy')
try:
    response = urllib.request.urlopen('http://httpbin.org/post',data=data)
    print (response.read().decode('utf-8'))
except Exception as e:
    print(e)

推荐阅读
cjavapy编程之路首页