如果不使用urllib2.Request()发送data参数,urllib2使用GET请求,GET请求和POST请求差别在于POST请求常有副作用,POST请求会通过某些方式改变系统的状态。也可以通过GET请求发送数据。
In [55]: import urllib2
In [56]: import urllib
In [57]: url='http://xxx/login.php'
In [58]: values={'ver' : 'xxx', 'email' : 'xxx', 'password' : 'xxx', 'mac' : 'xxx'}
In [59]: data=urllib.urlencode(values)
In [60]: full_url=url + '?' + data
In [61]: the_page=urllib2.urlopen(full_url)
In [63]: the_page.read()
Out[63]: '{"result":0,"data":0}'
默认情况下,urllib2使用Python-urllib/2.6 表明浏览器类型,可以通过增加User-Agent HTTP头
In [107]: import urllib
In [108]: import urllib2
In [109]: url='http://xxx/login.php'
In [110]: user_agent='Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
In [111]: values={'ver' : 'xxx', 'email' : 'xxx', 'password' : 'xxx', 'mac' : 'xxxx'}
In [112]: headers={'User-Agent' : user_agent}
In [114]: data=urllib.urlencode(values)
In [115]: req=urllib2.Request(url,data,headers)
In [116]: response=urllib2.urlopen(req)
In [117]: the_page=response.read()
In [118]: the_page
当给定的url不能连接时,urlopen()将报URLError异常,当给定的url内容不能访问时,urlopen()会报HTTPError异常
#/usr/bin/python
from urllib2 import Request,urlopen,URLError,HTTPError
req=Request('http://10.10.41.42/index.html')
try:
response=urlopen(req)
except HTTPError as e:
print 'The server couldn\'t fulfill the request.'
print 'Error code:',e.code
except URLError as e:
print 'We failed to fetch a server.'
print 'Reason:',e.reason
else:
print "Everything is fine"
这里需要注意的是在写异常处理时,HTTPError必须要写在URLError前面
#/usr/bin/python
from urllib2 import Request,urlopen,URLError,HTTPError
req=Request('http://10.10.41.42')
try:
response=urlopen(req)
except URLError as e:
if hasattr(e,'reason'):
print 'We failed to fetch a server.'
print 'Reason:',e.reason
elif hasattr(e,'code'):
print 'The server couldn\'t fulfill the request.'
print 'Error code:',e.code
else:
print "Everything is fine"
hasattr()函数判断一个对象是否有给定的属性
《Python开发技术详解》.( 周伟,宗杰).[高清PDF扫描版+随书视频+代码]
Python下使用MySQLdb模块