Python3 urllib.request.urlopen Example

The urllib.request.urlopen() function is used to implement access to the target url. This function will return an object which can be used to get the url webpage status and content data. The function prototype is as follows.

urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

1. urlopen Method Arguments.

Below is the function parameter description.

  1. url : The location of the target resource in the network. Can be said a URL string (such as:; It could also be a urllib.request object.
  2. data : Data is used to save data sent to the server request. The data default value is none, in this case the request method is http GET. When the data is not none, the request method is http POST.
  3. timeout : Set the access timeout for the url.
  4. cafile、capath、cadefault : Used to implement the HTTP requests of the trusted CA certificate.
  5. context : Implement SSL encryption transmission.

2. Return Object Methods.

When you use urlopen method to return a object. You can call the object methods to read the url page data and status information. Below will introduce the methods.

  1. info() : Returns an HTTPMessage object that represents the header information returned by the remote server.
  2. geturl() : Returns the requested url.
  3. getcode() : Returns the http status code. If it’s an HTTP request, 200 means requests complete successfully. 404 means url page not found.
  4. read(), readline(), readlines() : Read data from HTTPResponse.
  5. close() : Close the HTTP connection.