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

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())  
主站蜘蛛池模板: 宜春市| 青海省| 二连浩特市| 赞皇县| 青海省| 辽宁省| 东乌| 金乡县| 大安市| 苗栗市| 仙桃市| 普安县| 固始县| 邳州市| 重庆市| 平谷区| 和硕县| 新沂市| 石家庄市| 洛隆县| 达拉特旗| 攀枝花市| 平凉市| 太谷县| 冀州市| 嫩江县| 双桥区| 腾冲县| 前郭尔| 宜州市| 高唐县| 原阳县| 霍邱县| 泸水县| 北流市| 中山市| 云安县| 泰和县| 称多县| 滦平县| 西乡县|