- 论坛徽章:
- 0
|
国庆节在家里花了几天时间专研了一下子python,写了个从网上取某个网页并从网页中提取所需数据的小程序,遇到了一个奇怪的问题。在某种情况下,正常的except也会引发错误!
我的取网页的子程序是这样的:
- def get_htmlfile(url,proxies=None):
- if proxies: #if the proxies is provided
- proxystr='http://'+proxies
- _proxies={'http':proxystr}
- print 'Connecting the URL:%s \nwith proxies:%s...' % (url,proxystr)
- else:
- _proxies=None #there is no proxies by default
- print 'Connecting the URL:%s...' % (url)
- try:
- fp=urllib.urlopen(url,proxies=_proxies)
- data=fp.read()
- except IOError,(errno,strerror):
- print '\n\aI/O Error(%s): %s' % (errno,strerror)
- data=None
- except:
- print "Unexpected error:", sys.exc_info()[0]
- raise
-
- return data
复制代码
取网页的主程序是这样的(省略了后面无关部分):
- def main():
- proxy=None
- if len(sys.argv)<2:
- print __doc__
- sys.exit(1)
-
- if len(sys.argv)==3:
- proxy=sys.argv[2]
- filestr=get_htmlfile(sys.argv[1],proxy)
- if not filestr:
- print 'No data was got from web!'
- sys.exit(1)
- print 'Get the html file done!'
- print '\nNow analysis and extract the result from the html file...'
- 。。。。。。
复制代码
程序很简单,也无需多说,需要注意的是,关于子程序中except这部分,应该是标准的写法,没啥问题,对吧?
经过测试,程序也确实如预设那样运行的好好的:
1。通过代理访问本机的主页:
- admin@/cygdrive/c/users/Analysis# ./getResult.py http://localhost/ 172.28.30.80:8080
- Connecting the URL:http://localhost/
- with proxies:http://172.28.30.80:8080...
- Get the html file done!
- Now analysis and extract the result from the html file...
复制代码
2。停掉本机的webserver,再试一次:
程序也获得了预设的结果,无法打开网页,rasie一个错误,被except接收到。
- admin@/cygdrive/c/users/Analysis# ./getResult.py http://localhost/ 172.28.30.80:8080
- Connecting the URL:http://localhost/...
- I/O Error(socket error): (10061, 'Connection refused')
- No data was got from web!
复制代码
随后又将http://localhost换为正式的url也得到了正确的结果。嗯,我很有成就感,整理了一下程序,加了一些注释,存盘。睡觉!
可是今天,我又如常运行getResult.py去取数据,却出现了以下的错误:
- admin@/cygdrive/c/users/Analysis# ./getResult.py http://www.test.com/kjn 172.28.30.80:8080
- Connecting the URL:http://www.test.com/kjn/
- with proxies:http://172.28.30.80:8080...
- Traceback (most recent call last):
- File "./getResult.py", line 65, in ?
- main()
- File "./getResult.py", line 27, in main
- filestr=get_htmlfile(sys.argv[1],proxy)
- File "c:\users\Analysis\common.py", line 26, in get_htmlfile
- except IOError,(errno,strerror):
- ValueError: too many values to unpack
复制代码
咦,怎么except捉不到错误了?“too many values to unpack”这个错误也是我从没见过的错误,并且它好像不是右try内的语句而是except本身产生的!又试了几次,结果一样!经过检查程序是和昨天的一样,没做任何只是做了添加注释的操作,并且当时添加注释后测试也是正常的。我又试了一下取本机webserver的页面也是正常的。错误好像跟要取的页面有关,但为什么会出这个错呢?
各位大侠有何高见? |
|