requests库基本使用

requests库

get请求:

1.通过requests.get()来调用:

req = requests.get("http://www.baidu.com/")

2.添加header和查询参数:

如传入参数的get请求:

import requests
url = 'https://www.baidu.com/s'
kw = {
    'wd':'中国'
}
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
#params接收一个字典或者字符串的查询参数,字典类型自动转换为url编码,不需要urlencode()
response = requests.get(url=url,params=kw,headers=headers)
print(response.text)    

 

 查询参数:

print(response.text)        #返回Unicode格式的数据(str)
print(response.content)         #返回字节流数据(bytes)
print(response.url)        #查看完整url地址
print(response.encoding)          #查看响应头部字符编码
print(response.status_code)     #查看响应码

  

response.text和response.content的区别:

1.response.content:这个是直接从网络上面抓取的数据。没有经过任何解码。所以是一个bytes类型。其实在硬盘上和在网络上传输的字符串部是bytes类型。

2.response.text:这个是str的数据类型,将response.content进行解码的字符串。解码需要指定一个编码方式,requests会根据自己的猜测来判断编码的方式。所以有时候可能会猜测错误,就会导致解码产生乱码。这时候就应该使用”response.content.decode('utf-8')或者更多进行手动解码。

post请求:

1.基本post请求方法:

response = requests.post('https://www.baidu.com/',data=data)

2.传入data数据:

import requests

data = {
    'name':'tom','age':'22'
}
response = requests.post('http://httpbin.org/post', data=data)
print(response.text)

#print(response.json())    #输出为字典类型数据

使用代理:

使用requests 添加代理也非常简单,只要在请求的方法中(比如get或者post)传递proxies参数就可以了。

import requests

url = 'http://bj.xiaozhu.com/search-duanzufang-p{}-0/'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
    'Referer':'http://bj.xiaozhu.com/search-duanzufang-p{}-0/'
}
proxy = {    
    'http':'121.232.194.147:9000'
}    #代理服务器
response = requests.get(url=url,proxies=proxy,headers=headers)
with open('xiaozhu.html','w',encoding='utf-8') as fp:       #保存 
    fp.write(response.text)
print(response.text)    

cookie:

如果在一个响应中包含了cookie,那么可以利用 cookies属性拿到这个返回的cookie值:

#获取cookie
import requests

response = requests.get('http://www.baidu.com')
print(response.cookies)
print(type(response.cookies))
for k,v in response.cookies.items():        #.items() 遍历字典列表
    print(k+':'+v)

session:

会话对象。(使用多次请求中共享cookie)

requests库的session对象能够帮我们跨请求保持某些参数,也会在同一个session实例发出的所有请求之间保持cookies。

import requests

url = 'http://www.renren.com/SysHome.do'
data = {
    "email":"1617467747@qq.com",
    "password":"*******"
}
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
}
#登录
session = requests.session()
session.post(url=url,data=data,headers=headers)

#访问**个人中心
resp = session.get('http://www.renren.com/968214405/profile')
print(resp.text)

处理不信任的SSL信任的证书:

import requests
resp = requests.get("http://www.12386.cn/morshweb/", verify=False)  #verify=False     #意思是不需要验证ssl证书
print(resp.content.decode("utf-8"))

  

 

posted @ 2018-10-01 11:56  cmap  阅读(309)  评论(0编辑  收藏  举报