1、安装和文档地址
pip install requests
中文文档:http://docs.python-requests.org/zh_CN/latest/index.html
github地址:https://github.com/requests/requests
2、发送get请求
import requests
response=requests.get('http://www.baidu.com/')
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"}
#查看响应内容,response.text返回的是unicode格式的数据
print(response.text)
#查看响应内容,response.content返回的是字节流数据
print(response.content)
#查看完整url地址
print(response.url)
#查看响应头部字符编码
print(response.encoding)
#查看响应码
print(response.status_code)
3、发送post请求
import requests
url='https://www.lagou.com/jobs/positionAjax.json?city=%E6%B7%B1%E5%9C%B3&needAddtionalResult=false&isSchoolJob=0'
headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
'Referer':'https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput='}
data = {
'first': 'true',
'pn': 1,
'kd': 'python'
}
res=requests.post(url,headers=headers,data=data)
#如果是json数据,,直接调用json方法
print(res.json())
print(res.text)#获取网页内容
print(res.content)#获取网页内容
4、使用代理
import requests
url='http://httpbin.org/get'
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
}
proxy={'http':'171.14.209.180:27829'}
resp=requests.get(url,headers=headers,proxies=proxy)
#创建html文件,并将网址写入文件内
with open('xx.html','w',encoding='utf-8')as fp:
fp.write(resp.text)
5、cookie信息
如果在一个响应中包含了cookie
,那么可以利用cookies
属性拿到这个返回的cookie
值
import requests
url = "http://www.renren.com/PLogin.do"
data = {"email":"……",'password':"……"}
resp = requests.get('http://www.baidu.com/')
print(resp.cookies)
print(resp.cookies.get_dict())
6、session
之前使用urllib
库,是可以使用opener
发送多个请求,多个请求之间是可以共享cookie
的。那么如果使用requests
,也要达到共享cookie
的目的,那么可以使用requests
库给我们提供的session
对象。注意,这里的session
不是web开发中的那个session,这个地方只是一个会话的对象而已。以登录人人网为例,使用requests
来实现。
import requests
url = "http://www.renren.com/PLogin.do"
data = {"email":"……",'password':"p……r"}
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"
}
session=requests.session()
session.post(url,data=data,headers=headers)
resp=session.get('http://www.renren.com/880151247/profile')
print(resp.text)
7、处理不信任的SSL证书:
对于那些已经被信任的SSL整数的网站,比如https://www.baidu.com/
,那么使用requests
直接就可以正常的返回响应。示例代码如下
resp=requests.get('http://www.12306',verify=False)
print(resp.content.decode('utf-8'))
编码:unicide——str(encode)
解码:str——unicode(decode)
不同编码格式的字符串之间的互相转换编码格式的话,要先解码成unicode,在编码为其他编码格式的字符串。
str1.decode('gb2312')#表示将gb2312编码的字符串str1解码成unicode
str2.encode('utf-8')表示将unicode字符串str2编码的字符串转换成用utf-8格式