官术网_书友最值得收藏!

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())  
主站蜘蛛池模板: 弥渡县| 嘉鱼县| 长岭县| 大庆市| 开鲁县| 潼关县| 林州市| 和林格尔县| 松原市| 遂宁市| 阜宁县| 宁河县| 巢湖市| 武汉市| 甘肃省| 黎川县| 北海市| 林西县| 上高县| 西乌| 德化县| 临武县| 喀什市| 襄垣县| 闻喜县| 遂溪县| 安康市| 霍山县| 固安县| 壶关县| 台北县| 西昌市| 宣恩县| 永嘉县| 建德市| 黔东| 广元市| 崇阳县| 牙克石市| 札达县| 汾西县|