How to change the user agent header with Python urllib?

Sometimes, we want to change the user agent header with Python urllib.

In this article, we’ll look at how to change the user agent header with Python urllib.

How to change the user agent header with Python urllib?

To change the user agent header with Python urllib, we can call the build_opener method.

Then we set the addheaders attribute of the returned object to add the user-agent request header.

For instance, we write:

import urllib.request

opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'Mozilla/5.0')]
response = opener.open('http://www.example.com')
print(response)

We call urllib.request.build_opener method and assign the returned object to opener.

Then we set opener.addheaders attribute to [('User-Agent', 'Mozilla/5.0')] to set the user-agent header to Mozilla/5.0.

Next, we call opener.open with the URL we want to make a GET request to and assign the returned response to response.

Finally, we print the response.

Conclusion

To change the user agent header with Python urllib, we can call the build_opener method.

Then we set the addheaders attribute of the returned object to add the user-agent request header.