R
R
Russian Federation2016-03-27 15:24:05
Python
Russian Federation, 2016-03-27 15:24:05

What is the correct way to cast a try except exception on requests.exceptions.HTTPError?

I'm slowly learning Python.
For example, if you run the following command

import requests
r = requests.get('https://toster.ru/q/qwerty123v')
r.raise_for_status()

then an error pops up
Traceback (most recent call last):
  File "<string>", line 420, in run_nodebug
  File "C:\Users\Marat\Documents\first.py", line 8, in <module>
    r.raise_for_status()
  File "C:\Python34\lib\site-packages\requests\models.py", line 840, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://toster.ru/q/qwerty123v

Can't get rid of this error correctly.
I want to for-th go through certain links and see r.headers['content-type']
Maybe there are other ways of parsing?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Shogin, 2016-03-27
@mshogin

Why are you using raise_for_status?
I may not understand the terms, but something like this

import requests
test_urls = set([
    'http://habrahabr.ru',
    'https://toster.ru/q/qwerty123v'
])

for url in test_urls:
    r = requests.head(url)
    print("{:<50}: {}".format(url, r.headers['content-type']))

O
Oleg Drozdov, 2016-03-28
@Ardarick

from urllib.error import HTTPError

try:
    r.raise_for_status()
except HTTPError:
    continue
finally:
    Ваш код обработки

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question