John
John

Reputation: 1594

Python requests causing error on certain urls

For some reason when I try to get and process the following url with python-requests I receive an error causing my program to fail. Other similar urls seems to work fine

import requests

test = requests.get('http://t.co/Ilvvq1cKjK')
print test.url, test.status_code

What could be causing this URL to fail instead of just producing a 404 status code?

Upvotes: 1

Views: 177

Answers (1)

Jon Clements
Jon Clements

Reputation: 142216

The requests library has an exception hierarchy as listed here

So wrap your GET request in a try/except block:

import requests

try:
    test = requests.get('http://t.co/Ilvvq1cKjK')
    print test.url, test.status_code
except requests.exceptions.ConnectionError as e:
    print e.request.url, "*connection failed*"

That way you end up with similar behaviour to what you're doing now (so you get the redirected url), but cater for not being able to connect rather than print the status code.

Upvotes: 2

Related Questions