一、网络爬虫及应用
1.http请求的python实现
见前面。。。。。。。。这里只有概念性东西。。。。。。。。。。。。。。。。。
2.cookie的处理
自己手动添加cookie
3.基础
http响应码------response.code/response.getcode()
查看头部------response.headers/request.headers
4.重定向
要检测是否发生了重定向动作。只要检查下Response的URL和Request的URL是否一致就可以。
不想重定向,可以自定义
其中,urllib2是py2所用。现已被urllib.request包取代。
5.Proxy的设置
-----------------------------如下------------------------------------------------------------------
6.build_opener()与urllib.request.urlopen()
1.基础
urllib.request.urlopen()函数不支持验证、cookie或者其它HTTP高级功能。
要支持这些功能,必须使用build_opener()函数创建自定义Opener对象。
2.错误的处理
3.http的认证
4、代理的使用
2.使用urllib.request.install_opener()会设置全局opener,将使得所有HTTP访问均使用此代理。无益于程序使用不同的代理。
二、request库
1.request的完整请求和响应模型
1.1GET
1.2GET 多参数
2。POST
get 带参数 (链接)—params post带参数(副文)------data
3.加首部
需要传入HTTP Header时,我们传入一个dict作为headers参数:
>>> r = requests.get('https://www.douban.com/', headers={'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})
>>> r.text
'<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n <title>豆瓣(手机版)</title>...'
2.响应与编码
1.requests优势自动检测编码,可以使用encoding属性查看:
1.1chardet 检测
可见,用chardet检测编码,使用简单。获取到编码后,再转换为str,就可以方便后续处理。
2.requests对于特定类型的响应,例如JSON,可以直接获取:
>>> r = requests.get('https://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json')
>>> r.json()
{'query': {'count': 1, 'created': '2017-11-17T07:14:12Z', ...
3.requests默认使用application/x-www-form-urlencoded对POST数据编码。如果要传递JSON数据,可以直接传入json参数:
params = {'key': 'value'}
r = requests.post(url, json=params) # 内部自动序列化为JSON
4.上传文件需要更复杂的编码格式,但是requests把它简化成files参数
>>> upload_files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=upload_files)
在读取文件时,注意务必使用 rb 即二进制模式读取,这样获取的bytes长度才是文件的长度。
5.requests对获取HTTP响应的其他信息也非常简单
>>> r.headers
{Content-Type': 'text/html; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Content-Encoding': 'gzip', ...}
>>> r.headers['Content-Type']
'text/html; charset=utf-8'
6.requests对Cookie做了特殊处理,使得我们不必解析Cookie就可以轻松获取指定的Cookie:
>>> r.cookies['ts']
'example_cookie_12345'
7.指定超时,传入以秒为单位的timeout参数
>>> r = requests.get(url, timeout=2.5)
8.要在请求中传入Cookie,只需准备一个dict传入cookies参数:
>>> cs = {'token': '12345', 'status': 'working'}
>>> r = requests.get(url, cookies=cs)
1.session对象的妙用详解--------读取cookie-----------cookie是属性。
2.session 中cookie手动设置
1).优秀解法
2).繁琐
9、重定向和历史信息
10.代理设置