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

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())  
主站蜘蛛池模板: 青海省| 尼勒克县| 白银市| 黔江区| 襄汾县| 南岸区| 吉安县| 本溪| 杭锦旗| 五台县| 临漳县| 澎湖县| 江永县| 诏安县| 康平县| 延津县| 芮城县| 仙居县| 无棣县| 阜平县| 兴业县| 通许县| 泾川县| 朔州市| 桐城市| 霍山县| 屏南县| 朝阳县| 洛南县| 平顶山市| 赤城县| 隆林| 临武县| 涿鹿县| 成武县| 安国市| 保亭| 利津县| 鄂伦春自治旗| 寿阳县| 辛集市|