2013-07-21 59 views
1

我真的很努力地研究如何打印到列表。我想打印我指定的URL的服务器响应代码。你知道我怎么改变代码打印输出到列表中?如果不是,你知道我在哪里可以找到答案吗?我现在一直在寻找几个星期。Python打印列表问题

下面的代码:

import urllib2 
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]: 
    try: 
     connection = urllib2.urlopen(url) 
     print connection.getcode() 
     connection.close() 
    except urllib2.HTTPError, e: 
     print e.getcode() 

打印:

200 

200 

我想有:

[200, 200] 

回答

2

你真的想要一个列表?或者只是打印一个列表?在任何情况下,以下都应该工作:

import urllib2 
out = [] 
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]: 
    try: 
     connection = urllib2.urlopen(url) 
     out.append(connection.getcode()) 
     connection.close() 
    except urllib2.HTTPError, e: 
     out.append(e.getcode()) 
print out 

它只是使包含代码,然后打印列表的列表。

+1

差不多,您可能还想捕获Error上的代码。 – sberry

+0

我继续为你修复那部分。 – sberry

+0

太棒了。感谢@sberry和Matthew Wesly的快速回复! –