0.更换pip源到国内镜像
官网下载资源太慢了,经常出现socket.timeout
永久更换
windows下,直接在user目录中创建一个pip目录,如:C:\Users\xx\pip,然后新建文件pip.ini,在pip.ini文件中输入以下内容(以清华镜像为例):
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = https://pypi.tuna.tsinghua.edu.cn
(创建ini文件可以用sublime text3)
1.requests库安装
windows+R
cmd
pip install requests
2.requests库方法

3.爬取网络的通用代码框架

主要验证爬取有没有成功,状态码200成功,404失败。
r.encoding根据header中的charset猜测
r.apparent_encoding根据内容分析
ISO-8859-1
utf-8
requests.ConnectionError连接远程服务器超时异常
requests.Timeout请求URL超时,产生超时异常
r.raise_for_status()
4.HTTP协议
URL格式 http://host[:port][path]
host:合法的Internet主机域名或IP地址
port:端口号,缺省端口为80
path:请求资源的路径
post,put和patch的区别
POST:资源后附加新数据
PUT:覆盖
PATCH:替换
区分requests.head和r.headers
5.robots协议
Robots Exclusion Standard网络爬虫排除标准
根目录网页后面加/robots.txt
*表示所有
/表示根目录
类人类行为可不参考robots协议
6.实例
r.encoding为503,可能为user-agent不对,可通过键字对进行替换
kv={'user-agent':‘Mozilla/5.0’}
r.requests.get(url,headers=kv)
百度关键词检索
kv={‘wd’:“Python”}
r=r.requests.get("http://www.baidu.com/s",params=kv)
字典类型dictionary
格式:d={"中国":“北京”,“美国:“华盛顿””}
方法:
del d[k]
k in d
d.keys()
d.values()
d.items()
其中,k为key,括号不可省略
d.get(k,<default>)
d.pop(k,<default>)
7.爬取表格
中文对齐问题(中英文混合输出)
chr(12288)