I have some code that pulls incomplete URLs from an API and appends these to a base URL. I am trying to extend this to test each URL to make sure it does not lead to a 404 before printing out to screen.
I looked over other answers on how to use urllib with python3 and thought I had done everything correctly, however, I am getting the error in the title.
testurl
is my request and resp
is my response. This is the code I am using:
testurl=urllib.request.urlopen("http://www.google.com")
try:
resp = urllib.request.urlopen(testurl)
except urllib.error.HTTPError as e:
if e.code == 404:
blah = 1
else:
print("it worked!")
What am I missing?
The full error output:
Traceback (most recent call last):
File "imgtst.py", line 27, in <module>
resp = urllib.request.urlopen(testurl)
File "/usr/local/lib/python3.7/urllib/request.py", line 222, in urlopen
return opener.open(url, data, timeout)
File "/usr/local/lib/python3.7/urllib/request.py", line 517, in open
protocol = req.type
AttributeError: 'HTTPResponse' object has no attribute 'type'
edit:
After the problem is pointed out due to Bruno's answer, I try the following code instead:
try:
resp = urllib.request.urlopen("http://www.google.com")
except urllib.error.HTTPError as e:
if e.code == 404:
print("error")
else:
print("it worked")
However, this results in nothing being printed at all.