Skip to content

Tag: urllib

Python3: JSON POST Request WITHOUT requests library

I want to send JSON encoded data to a server using only native Python libraries. I love requests but I simply can’t use it because I can’t use it on the machine which runs the script. I need to do it without. My server is a local WAMP server. I always get an urllib.error.HTTPError: HTTP Error 500:…

Only add to a dict if a condition is met

I am using urllib.urlencode to build web POST parameters, however there are a few values I only want to be added if a value other than None exists for them. That works fine, however if I make the orange variable optional, how can I prevent it from being added to the parameters? Something like this (pseudocode…

How to urlencode a querystring in Python?

I am trying to urlencode this string before I submit. Answer You need to pass your parameters into urlencode() as either a mapping (dict), or a sequence of 2-tuples, like: Python 3 or above Use urllib.parse.urlencode: Note that this does not do url encoding in the commonly used sense (look at the output). For…

How do I catch a specific HTTP error in Python?

I have but what I end up is catching any kind of HTTP error. I want to catch only if the specified webpage doesn’t exist (404?). Answer Python 3 Python 2 Just catch HTTPError, handle it, and if it’s not Error 404, simply use raise to re-raise the exception. See the Python tutorial. Here is a compl…

Can’t download YouTube video

I’m having trouble retrieving the YouTube video automatically. Here’s the code. The problem is the last part. download = urllib.request.urlopen(download_url).read() There’s an error message (thanks Wooble): Answer The code on the original question relies on several assumptions about the content of YouTube pag…