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

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())  
主站蜘蛛池模板: 西畴县| 鹤庆县| 博罗县| 平陆县| 民丰县| 桑植县| 莱州市| 东乡族自治县| 泾川县| 中牟县| 准格尔旗| 洱源县| 唐山市| 孟州市| 锦屏县| 女性| 泰兴市| 阿拉善盟| 耒阳市| 阿克陶县| 化州市| 年辖:市辖区| 玉林市| 乌苏市| 兴和县| 西乌珠穆沁旗| 高尔夫| 财经| 新巴尔虎左旗| 方山县| 交城县| 景洪市| 略阳县| 普兰县| 镇安县| 旬邑县| 株洲县| 扬州市| 鄂托克旗| 普定县| 都江堰市|