最基本的GET请求可以直接用get方法
response = requests.get("http://www.baidu.com/")
# 也可以这么写
# response = requests.request("get", "http://www.baidu.com/")
添加 headers 和 查询参数
如果想添加 headers,可以传入headers
参数来增加请求头中的headers信息。如果要将参数放在url中传递,可以利用 params
参数。
import requests
kw = {'wd':'长城'}
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
# params 接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get("http://www.baidu.com/s?", params = kw, headers = headers)
# 查看响应内容,response.text 返回的是Unicode格式的数据
print response.text
# 查看响应内容,response.content返回的字节流数据
print respones.content
# 查看完整url地址
print response.url
# 查看响应头部字符编码
print response.encoding
# 查看响应码
print response.status_code
运行结果:
......
......
'http://www.baidu.com/s?wd=%E9%95%BF%E5%9F%8E'
'utf-8'
200
使用response.text 时,Requests 会基于 HTTP 响应的文本编码自动解码响应内容,大多数 Unicode 字符集都能被无缝地解码。
使用response.content 时,返回的是服务器响应数据的原始二进制字节流,可以用来保存图片等二进制文件。