Ali Ali - 4 months ago 8
Python Question

Unable to handle "HTTP Badstatus line" exception

I want to handle

http.client.BadStatusLine: ''
exception.
I am on python3. My code is

import http.client

try:
req = urllib.request.Request(url, headers={'User-Agent': 'Chrome/51'})
html = urllib.request.urlopen(req).read()
soup = BeautifulSoup(html,"html.parser")
return soup
except http.client.HTTPException as eror:
print("Boom")


but
httpException
is not in python3? Figure

I read stackOverFloeQuestion and this but unable to catch it. Any help?

Answer

You need to make up your mind :-). You can either use http.client or urllib.request, but you should not use one and then try to catch errors from the other. If you want to stick with urllib.request, the class to catch is urllib.error.HTTPError.

Perhaps it may be more opportune in your case to use Requests, which is a higher level http library.