Python Penetration Testing Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

We use custom user agent string in the request as following:

  1. First, import the required modules:
>>> import urllib.request  
  1. Then define the user agent we plan to specify for the request:
>>> user_agent = ' Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:47.0) Gecko/20100101 Firefox/47.0'  
  1. Set up the headers for the request:
>>> headers = {'User-Agent': user_agent}  
  1. Create the request as follows:
>>> request = urllib.request.Request("https://www.packtpub.com/", headers=headers)  
  1. Request the web page with urlopen:
>>> with urllib.request.urlopen(request) as response:
...     with open('with_new_user_agent.html', 'wb') as out:
...         out.write(response.read())