requests模块的一些总结
一.cookie模拟登录的三种方式
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#author tom import requests
post_url='http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp=20192012211'
post_data={"email":"302624476@qq.com","password":"xxx"}
headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36"}
session=requests.session()
#使用session发送post请求,cookie保存在其中
session.post(url=post_url,data=post_data,headers=headers) #在session请求登录之后才能获取的网址
r=session.get("http://www.renren.com/323264874/profile",headers=headers) with open('renren.html','w',encoding='utf-8') as f:
f.write(r.content.decode()) # request模拟登陆的三种方式:
#方式一:
# 先实例化一个session对象,用session先发起一个post请求,session就保存了cookie,再用session发起登录后的请求 #方式二
#浏览器挡登陆后拿到cookie
# 在headers中添加cookie的键值对 # 方式三
#在请求方法中添加cookies参数,接收字典形式的cookies
# 字典形式的cookie中的键是cookie中name对应的值,值是cookie中value对应的之
#和方式二有点类似,就是拿到cookie,改造成字典,然后在请求时候设置cookies参数
关于方式三的扩展:
- requests.utils.dict_from_cookiejar()
def test_url(ip,is_http,redis=None):
pro = {TYPES[is_http]:ip}
#if redis == None:
# redis = redis.StrictRedis(REDIS_SERVER,REDIS_PORT,DB_FOR_IP)
time = 0
flag= False
try:
#print "test url:",i,ip,pro
r = None
cookie_old = None
if STORE_COOKIE and redis != None:
cookie_old = redis.get(ip)
#print "old cookie:",cookie
if cookie_old != None and cookie_old != "None" and cookie_old != "{}":
#print "use cookie"
log.debug("PID:%d IP:%s use old cookies:%s " % (os.getpid(),ip,cookie_old))
cookies = cookiejar_from_dict(json.loads(cookie_old))
r = requests.get(TEST_URL,proxies=pro,cookies=cookies,timeout=SOKCET_TIMEOUT)
else:
if USE_DEFAULT_COOKIE:
rand_cookies = {"bid":random_str()}
log.debug("PID:%d IP:%s use random cookies:%s " % (os.getpid(),ip,str(rand_cookies)))
cookie = cookiejar_from_dict(rand_cookies)
r = requests.get(TEST_URL,proxies=pro,cookies=cookie,timeout=SOKCET_TIMEOUT)
else:
r = requests.get(TEST_URL,proxies=pro,timeout=SOKCET_TIMEOUT)
else:
if USE_DEFAULT_COOKIE:
cookie = cookiejar_from_dict({"bid":random_str()})
r = requests.get(TEST_URL,proxies=pro,cookies=cookie,timeout=SOKCET_TIMEOUT)
else:
r = requests.get(TEST_URL,proxies=pro,timeout=SOKCET_TIMEOUT)
time += r.elapsed.microseconds/1000
log.debug("PID:%d Test IP:%s result:%d time:%d type:%s" % (os.getpid(),ip,r.status_code,time,TYPES[is_http]))
if r.ok:
flag = True
if STORE_COOKIE and redis != None:
#print "new cookies:",r.cookies
if r.cookies != None :
cookie = json.dumps(dict_from_cookiejar(r.cookies))
if cookie and cookie != "{}" and cookie_old != cookie:
log.debug("PID:%d IP:%s new cookies:%s old cookies:%s" % (os.getpid(),ip,cookie,cookie_old))
redis.set(ip,cookie)
except Exception as e:
log.debug("PID:%d error:%s" % (os.getpid(),e.message))
return flag,time
可参考:http://codingdict.com/sources/py/requests.utils/18814.html
二.requests编码问题
1.response.text
- 类型:str
- 解码方式:根据HTTP头部对应的编码做出有根据的推测,推测文本的编码内容
- 如何修改编码方式:response.encoding="指定的编码方式"
2.response.content
- 类型:bytes
- 解码类型:没有指定
- 如何修改编码方式:response.content.deocode("编码方式")
注意:更建议使用第二种,原汁原味,过早的预处理不是好结果
三.url的编码解码
1.requests.utils.unquote(url)
2.requests.utils.quote(url)
requests模块的一些总结的更多相关文章
- 爬虫requests模块 1
让我们从一些简单的示例开始吧. 发送请求¶ 使用 Requests 发送网络请求非常简单. 一开始要导入 Requests 模块: >>> import requests 然后,尝试 ...
- requests 模块
发送请求 使用Requests发送网络请求非常简单. 一开始要导入Requests模块: >>> import requests 然后,尝试获取某个网页.本例子中,我们来获取Gith ...
- requests模块--python发送http请求
requests模块 在Python内置模块(urllib.urllib2.httplib)的基础上进行了高度的封装,从而使得Pythoner更好的进行http请求,使用Requests可以轻而易举的 ...
- Python requests模块学习笔记
目录 Requests模块说明 Requests模块安装 Requests模块简单入门 Requests示例 参考文档 1.Requests模块说明 Requests 是使用 Apache2 Li ...
- Python高手之路【八】python基础之requests模块
1.Requests模块说明 Requests 是使用 Apache2 Licensed 许可证的 HTTP 库.用 Python 编写,真正的为人类着想. Python 标准库中的 urllib2 ...
- Python requests模块
import requests 下面就可以使用神奇的requests模块了! 1.向网页发送数据 >>> payload = {'key1': 'value1', 'key2': [ ...
- 基于python第三方requests 模块的HTTP请求类
使用requests模块构造的下载器,首先安装第三方库requests pip install requests 1 class StrongDownload(object): def __init_ ...
- 使用requests模块爬虫
虽然干技术多年了,但从没有写过博客,想来甚是惭愧,本篇作为我博客的第一篇,也是测试篇.不为写的好,只为博诸君一眸而已. 使用python爬虫,有几个比较常用的,获取html_content的模块url ...
- [实战演练]python3使用requests模块爬取页面内容
本文摘要: 1.安装pip 2.安装requests模块 3.安装beautifulsoup4 4.requests模块浅析 + 发送请求 + 传递URL参数 + 响应内容 + 获取网页编码 + 获取 ...
- python爬虫之requests模块介绍
介绍 #介绍:使用requests可以模拟浏览器的请求,比起之前用到的urllib,requests模块的api更加便捷(本质就是封装了urllib3) #注意:requests库发送请求将网页内容下 ...
随机推荐
- c++(重载等号=操作为深拷贝)
// ConsoleApplication19.cpp : 定义控制台应用程序的入口点. // #pragma warning(disable:4996) #include "stdafx. ...
- Oracle——分组函数
AVG(平均值)和 SUM (合计)函数 可以对数值型数据使用AVG 和 SUM 函数. AVG组函数忽略空值 --在组函数中使用NVL函数 --求平均值 )) MIN(最小值)和 MAX(最大值)函 ...
- Mybatis XML 配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC ...
- 【Android学习】Android工程资源命名禁忌
在制作一个继续按钮时,将button的id设置为continue,发现报了错误,error: invalid symbol: 'continue' 一开始还以为是编码问题,后来百度之后才知道安卓And ...
- Git代码冲突常见解决方法
在发布这个配置文件的时候,会发生代码冲突: error: Your local changes to the following files would be overwritten by merge ...
- delphi json用法
用法:uses Superobject, Sperjsondelphi里有json单元. procedure TForm2.SuperObjectClick(Sender: TObject); var ...
- JQuery中一些常用函数的运用
一.JQuery的效果介绍 二.定时弹出广告图片JQ部分代码 <script type="text/javascript"> var time; $(function( ...
- WP REST API: 设置和使用OAuth 1.0a Authentication(原文)
In the previous part of the series, we set up basic HTTP authentication on the server by installing ...
- React 使用browserHistory项目访问404问题
最近项目里面用到了React但是发布到iis站点之后,路由地址 刷新访问直接404错误.查阅资料之后发现是iis缺少配置URL重写 的问题导致的.下面我们来图形化配置,简单的配置下IIS 打开IIS使 ...
- R:魔兽世界终极版
描述 魔兽世界的西面是红魔军的司令部,东面是蓝魔军的司令部.两个司令部之间是依次排列的若干城市,城市从西向东依次编号为1,2,3 .... N ( N <= 20 ).红魔军的司令部算作编号为0 ...