Python Forum

Full Version: urllib request error 404
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hey there,

I'm not able to obtain my response from one of two YouTube links in a document with the google API.

Here is the code:
import urllib.request
from random import randint

'''
content of youtubeMusicPlaylist.txt:

https://www.youtube.com/watch?v=V6g172aoZb4
https://www.youtube.com/watch?v=ksrnQ7i82T0
'''

def getLineByIndex(lineIndex):
    try:
        with open('youtubeMusicPlaylist.txt', 'r') as file:
            for i, line in enumerate(file):
                if i == lineIndex:
                    return line

                if i > lineIndex:
                    print('out of bounds error while reading lines')
                    exit(0)

            return -1
    except IOError:
        print('cannot access file: youtubeMusicPlaylist.txt')
        exit(0)

link = getLineByIndex(randint(0, 1))

index = link.find('v=')
link = link[index+2:]
index = link.find('&t=')

if index != -1:
    link = link[:index]

key="1234567"
searchUrl="https://www.googleapis.com/youtube/v3/videos?id="+link+"&key="+key+"&part=contentDetails"
response = urllib.request.urlopen(searchUrl).read()
print(response)
Some links are working fine, but most of them do not.

Here is the error message:

Error:
Traceback (most recent call last): File "C:\Users\root\Desktop\RaspberryHomeProject2\test.py", line 31, in <module> response = urllib.request.urlopen(searchUrl).read() File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 222, in urlopen return opener.open(url, data, timeout) File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 531, in open response = meth(req, response) File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 641, in http_response 'http', request, response, code, msg, hdrs) File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 569, in error return self._call_chain(*args) File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 503, in _call_chain result = func(*args) File "C:\Users\root\AppData\Local\Programs\Python\Python37-32\lib\urllib\request.py", line 649, in http_error_default raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 404: Not Found
When I set the video link id manually into the string, it will work without problems by the way.
The problem may be located in the link variable that will be passed to the request.

Can somebody help me out?

Thanks!
I solved the problem by not using urllib but the requests module to get the html data.
Quote:but the requests module to get the html data.
Good move!