Pregunta

I'm really struggling to work out how to print to a list. I'd like to print the server response codes of URLs I specify. Do you know how I'd alter to code to print the output into a list? If not, do you know where I'd find the answer? I've been searching around for a couple of weeks now.

Here's the code:

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()

prints:

200

200

I'd like to have:

[200, 200]
¿Fue útil?

Solución

Do you actually want a list? Or just to print it like a list? In either case the following should work:

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

It just makes a list containing the codes, then prints the list.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top