前言
在学习Scrapy爬虫的过程中,发现需要总结一些东西来避免自己遗忘。这是咸鱼的第19篇原创。
关于requests基本使用方法参照中文版参考文档: http://docs.python-requests.org/zh_CN/latest/index.html
response.text
类型:str
解码类型: 根据HTTP 头部对响应的编码作出有根据的推测,推测的文本编码
如何修改编码方式:response.encoding=”gbk”
response.content
类型:bytes
解码类型:没有指定
如何修改编码方式:response.content.deocde(“utf8”)
更推荐使用response.content.deocde()的方式获取响应的html页面
requests.get("http://www.baidu.com", proxies = proxies)
proxies = {
"http": "http://12.34.56.79:9527",
"https": "https://12.34.56.79:9527",
}
代理的基本原理
正向代理:浏览器明确知道要访问的是什么服务器,只不过目前无法达到,需要通过代理来帮助完成这个请求操作。
反向代理:浏览器不知道任何关于要请求的服务器的信息,需要通过Nginx请求。
session = requests.session()
response = session.get(url,headers)
#把cookie对象转化为字典
reqeusts.util.dict_from_cookiejar
#把字典转化为cookie对象
reqeusts.util.cookiejar_from_dict
#url解码
reqeusts.util.unquote()
#url编码
reqeusts.util.quote()
#忽略SSL证书验证
response = requests.get("https://www.12306.cn/mormhweb/ ", verify=False)
#请求https的网站忽略SSL证书验证之后还是会出现警告信息,在请求前加上下面这句就可以禁用安全请求警告
#InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)
requests.packages.urllib3.disable_warnings()
json.loads() #json字符串转化为python数据类型
json.dumps() #python数据类型转化为json字符串
json.load() #包含json的类文件对象转化为python数据类型
json.dump() #python数据类型转化为包含json的类文件对象
具有read()或者write()方法的对象就是类文件对象,f =open(‘a.txt’,‘r’) f
就是类文件对象
json文件出现中文乱码:ensure_ascii=False
json、字典格式化输出: indent=2
json格式化打印: 使用pprint
使用前需要pip install pprint
安装
pprint效果图