python之requests使用

requests比request使用更方便灵活

1.get的使用

import requests

data = {
"wd":"章子怡"
}

headers = {
"User-Agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36"
}

#字典类型自动转码,不需要urlencode()
response = requests.get("https://www.baidu.com/s?",params=data,headers=headers)

#response = requests.post(base_url,data=data,headers=headers)      #post用的是data=,而get使用的是params=,注意区分

#也可以写成下面这种形式

#response = requests.request('get',"https://www.baidu.com/s?",params=data,headers=headers)

 

 

 #返回的response可以查看很多东西

#response.text返回的是Unicode数据
print(response.text)

#查看响应内容,返回的是字节流的数据
print(response.content)   #urllib----response.read()

#查看完整的url地址
print(response.url)

#查看响应头
print(response.headers)

#查看响应头部字符编码
print(response.encoding)

#查看状态码
print(response.status_code)

2.代理的使用

#私密代理验证
# 格式:用户名:密码@主机IP:端口
value = "dr_dao_hacker:abbrty9r@31.156.178.150:16861"
proxy = {"http":value}
response = requests.get("http://www.baidu.com",proxies=proxy)

#根据协议类型选择不同的代理
proxies = {
"http":"182.202.222.155:61234",
 "https":"50.233.137.36:80"
 }
response = requests.request("get","https://www.baidu.com/",proxies=proxies)

3.含有cookie的使用

#1.创建session,可以保存cookie值

ssion = requests.session()

#2.

data= { "email":"18811176626", "password":"123456"}
#发送附带用户名和密码的请求,并获取登录后的cookies,保存在session对象当中
ssion.post("http://www.renren.com/PLogin.do",data=data)
print("~~~~~~~~~~~~~~~~~~~~登录完成~~~~~~~~~~~~~~~~~~~~~~~")
#个人首页
response = ssion.get("http://www.renren.com/964508169/profile")

posted on 2018-03-24 23:32  风过竹影  阅读(217)  评论(0编辑  收藏  举报