–安装爬虫需要的库
C:\python37>pip install requests
Collecting requests
Downloading https://files.pythonhosted.org/packages/7d/e3/20f…84b/requests-2.21.0-py2.py3-none-any.whl (57kB)
100% |████████████████████████████████| 61kB 225kB/s
Collecting urllib3<1.25,>=1.21.1 (from requests)
Downloading https://files.pythonhosted.org/packages/62/00/ee1…79e/urllib3-1.24.1-py2.py3-none-any.whl (118kB)
100% |████████████████████████████████| 122kB 585kB/s
Collecting idna<2.9,>=2.5 (from requests)
Downloading https://files.pythonhosted.org/packages/14/2c/cd55…4c9/idna-2.8-py2.py3-none-any.whl (58kB)
100% |████████████████████████████████| 61kB 1.3MB/s
Collecting chardet<3.1.0,>=3.0.2 (from requests)
Downloading https://files.pythonhosted.org/packages/bc/a9/01ffe…b8/chardet-3.0.4-py2.py3-none-any.whl (133kB)
100% |████████████████████████████████| 143kB 267kB/s
Collecting certifi>=2017.4.17 (from requests)
Downloading https://files.pythonhosted.org/packages/9f/e0/ac…e8a/certifi-2018.11.29-py2.py3-none-any.whl (154kB)
100% |████████████████████████████████| 163kB 273kB/s
Installing collected packages: urllib3, idna, chardet, certifi, requests
Successfully installed certifi-2018.11.29 chardet-3.0.4 idna-2.8 requests-2.21.0 urllib3-1.24.1
什么是Urllib
Python内置的Http请求库
urllib.request 请求模块 模拟浏览器
urllib.error 异常处理模块
urllib.parse url解析模块 工具模块,如:拆分、合并
urllib.robotparser robots.txt 解析模块
urllib是Python自带的标准库,无需安装,直接可以用。
提供了如下功能:
网页请求
响应获取
代理和cookie设置
异常处理
URL解析
爬虫所需要的功能,基本上在urllib中都能找到,学习这个标准库,可以更加深入的理解后面更加便利的requests库。
2和3的区别
Python2
import urllib2
response = urllib2.urlopen(‘http://www.baidu.com’);
Python3
import urllib.request
response =urllib.request.urlopen(‘http://www.baidu.com’);
用法:
urlOpen 发送请求给服务器。
urllib.request.urlopen(url,data=None[参数],[timeout,]*,cafile=None,capath=None,cadefault=false,context=None)
例子:
import urllib.requests
response=urllib.reqeust.urlopen(‘http://www.baidu.com’)
print(response.read().decode(‘utf-8’))