赣南脐橙

keybr

佰草伐

导航

python发送get请求

    使用urllib和urllib2模块,发送get请求,urllib和urllib2模块需要time模块配合一起使用。php知识网

        python2.7发送get请求代码:

Python
#!/usr/bin/python
# -*- coding=utf8 -*-
import time
import urllib
import urllib2

req = urllib2.Request("http://blog.cuteur.cn?id=1")
opener = urllib2.build_opener()
resp = opener.open(req)
content = resp.read()
print content

        如果请求失败的异常捕获:

Python
#!/usr/bin/python
# -*- coding=utf8 -*-
import time
import urllib
import urllib2

try:
    req = urllib2.Request("http://blog.cuteur.cn?id=1")
    opener = urllib2.build_opener()
    resp = opener.open(req)
    content = resp.read()
    print content  
except httplib.HTTPException, e:
    raise str(e)
except urllib2.HTTPError, e:
    print "err code:%s, message:%s" % (e.code ,httplib.responses[e.code])
    raise str(e)
except urllib2.URLError, e:
    raise str(e)
except:
    raise "请求失败 error"

posted on 2020-07-29 17:11  佰草伐  阅读(409)  评论(0编辑  收藏  举报

keybr

php基础知识

Wood Furniture