Requests:让http服务人类
虽然Python标准库中的urllib模块包含了平常我们使用的大多数功能,但是它的API使用起来让人感觉不太好,而Request自称”HTTP for Humans“,说明使用更简单方便。
Request唯一的非转基因的Python库,人类可以安全享有,
Request继承了urllib的所有特性,Request支持HTTP链接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动确定响应内容的编码。支持国际化的URL和POST的数据自动编码。
request的安装方式
pip install requests
基于GET请求(headers参数和params参数)
如果想添加headers,可以传入headers参数来增加请求头中headers信息,如果要将参数放在url中传递,可以利用params参数。
# coding=utf-8
import requests
headers = {"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"}
p = {"wd":"明朝那些事"}
url_temp = "https://www.baidu.com/s?"
url_temp = "https://www.baidu.com/s"
#params接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
r = requests.get(url_temp,headers=headers,params=p)
#查看响应内容,r.text返回的是unicode格式的数据
print(r.text)
#查看响应内容,r.content返回的字节流数据
print(r.content)
#查看完整的url地址
print(r.url)
#查看响应码
print(r.status_code)
#查看响应头部字符编码
print(r.encoding)
url = "https://www.baidu.com/s?wd={}".format("明朝那些事")
r = requests.get(url,headers=headers)
print(r.status_code)
print(r.request.url)
- 使用r.text 时,Requests会基于HTTP相应的文本编码自动解码响应的内容,大多数Unicode字符集都能被无缝的解码。
- 使用r.content时,返回的是服务器响应数据的原始二进制字节流,可以用来保存图片等二进制文件。
#coding=utf-8
import requests
response = requests.get("http://www.sina.com")
print(response.request.headers)
print(response.content.decode())
结果
{'User-Agent': 'python-requests/2.12.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
<!DOCTYPE html>
<!-- [ published at 2017-06-09 15:15:23 ] -->
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>新浪首页</title>
<meta name="keywords" content="新浪,新浪网,SINA,sina,sina.com.cn,新浪首页,门户,资讯" />
...
#coding=utf-8
import requests
response = requests.get("http://www.sina.com")
print(response.request.headers)
print(response.text)
{'User-Agent': 'python-requests/2.12.4', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive'}
<!DOCTYPE html>
<!-- [ published at 2017-06-09 15:18:10 ] -->
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>新浪首页</title>
<meta name="keywords" content="新浪,新浪网,SINA,sina,sina.com.cn,新浪首页,门户,资讯" />
<meta name="description" content="新浪网为全çƒç”¨æˆ·24å°æ—¶æ供全é¢åŠæ—¶çš„ä¸æ–‡èµ„讯,内容覆盖国内外çªå‘新闻事件ã€ä½“å›èµ›äº‹ã€å¨±ä¹æ—¶å°šã€äº§ä¸šèµ„讯ã€å®žç”¨ä¿¡æ¯ç‰ï¼Œè®¾æœ‰æ–°é—»ã€ä½“育ã€å¨±ä¹ã€è´¢ç»ã€ç§‘技ã€æˆ¿äº§ã€æ±½è½¦ç‰30多个内容频é“,åŒæ—¶å¼€è®¾åšå®¢ã€è§†é¢‘ã€è®ºå›ç‰è‡ªç”±äº’动交æµç©ºé—´ã€‚" />
<link rel="mask-icon" sizes="any" href="//www.sina.com.cn/favicon.svg" color="red">
`
产生问题的原因:
- request自带的Accept-Encoding导致或者新浪默认发送的就是压缩之后的网页
- 但是为什么content没有问题,因为requests自带解压压缩网页的功能。
- 当收到一个响应时,Requests会猜测响应的编码格式,用于当调用response.text方法时对响应进行解码。Requests首先在HTTP头部检测是否存在指定的编码格式,如果不存在则会使用chart-detect来猜测编码方式(存在误差)
- 最好使用response.content.decode()