Python爬虫基础之Cookie
一、Cookie会话
简单地说,cookie就是存储在用户浏览器中的一小段文本文件。Cookies是纯文本形式,它们不包含任何可执行代码。一个Web页面或服务器告之浏览器来将这些信息存储并且基于一系列规则在之后的每个请求中都将该信息返回至服务器。当服务器收到浏览器请求附带的Cookie会话信息,会认为浏览器发出的请求是合法的,是经过身份验证的。否则,会拒绝浏览器的请求。

二、访问需要登录态Cookie的页面
1.使用opener.open()方式
import urllib.request
import urllib.parse
import re
import http.cookiejar
import urllib.error user_agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4'
# 初始化headers
headers = {'User-Agent': user_agent}
url = 'http://xxx.xxx.com/auth/valid.json'
cookie_filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(cookie_filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler) try:
# 登录分期乐
params = {'uin': 'xxxxx', 'passwd': 'xxxxxx', 'imgcode': '',
'_1': '', '_2': '', '_3': '', 'url': ''
}
data = urllib.parse.urlencode(params).encode(encoding='utf-8', errors='ignore')
request = urllib.request.Request(url, data=data, headers=headers, method='POST')
response = opener.open(request)
buff = response.read()
html = buff.decode('utf-8')
cookie.save(ignore_discard=True, ignore_expires=True) # 保存cookie到cookie.txt中
for item in cookie:
print('Name = ' + item.name)
print('Value = ' + item.value)
if re.search('ok', html):
print('login success')
# 访问需要登录态Cookie的页面
target_url = 'http://order.xxxxxx.com/order/list.html'
request = urllib.request.Request(target_url, headers=headers, method='GET')
response = opener.open(request)
print(response.read().decode('utf-8'))
else:
print('login fail')
except urllib.error.HTTPError as e:
print(e.reason)
except urllib.error.URLError as e:
print(e.reason)
现在我们来分析下以上的代码,怎么保存并把cookie传递到后续每个需要登录态的请求:
cookie_filename = 'cookie.txt'cookie = http.cookiejar.MozillaCookieJar(cookie_filename)
cookie.save(ignore_discard=True, ignore_expires=True)
引用http.cookiejar.MozillaCookieJar类声明一个FileCookieJar对象cookie,cookie可以用来把请求获取到的cookie会话信息保存到以cookie_filename命名的文件中,还可以在页面请求时从cookie文件中加
载会话信息并作为请求头参数Cookie。
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
引用urllib.request.HTTPCookieProcessor类声明一个handler对象,用来处理http cookie会话信息,并把它作为参数传递给urllib.request.build_opener,设置成全局的http handler处理器,这样使用
opener.open()的请求都会带上之前保存的cookie会话信息。
2.使用urllib.request.urlopen()方式
try:
# 登录分期乐
params = {'uin': 'xxxxxx', 'passwd': 'xxxxxx', 'imgcode': '',
'_1': '', '_2': '', '_3': '', 'url': ''
}
data = urllib.parse.urlencode(params).encode(encoding='utf-8', errors='ignore')
request = urllib.request.Request(url, data=data, headers=headers, method='POST')
response = opener.open(request)
buff = response.read()
html = buff.decode('utf-8')
cookie.save(ignore_discard=True, ignore_expires=True) # 保存cookie到cookie.txt中
order_cookie = []
for item in cookie:
print('Name = ' + item.name)
print('Value = ' + item.value)
e = (item.name, item.value) # 转换为元祖,保存到列表中
order_cookie.append(item.name + '=' + item.value) order_cookie = ';'.join(order_cookie) # 拼接成a=b;c=d;格式字符串
if re.search('ok', html):
print('login success')
# 访问需要登录态Cookie的页面
target_url = 'http://order.xxxxxx.com/order/list.html'
order_headers = {
'User-Agent': user_agent,
'Cookie': order_cookie # 请求头带上Cookie
}
request = urllib.request.Request(target_url, headers=order_headers, method='GET')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
else:
print('login fail')
except urllib.error.HTTPError as e:
print(e.reason)
except urllib.error.URLError as e:
print(e.reason)
与opener.open()方式相比,通过urllib.request.urllib发送请求方式稍微复杂些,首先需要遍历返回的登录态的cookie,转换为元素并保存到列表orderlist里面,再通过字符串join(seq)方法拼接成字符串,最后以字典格式添加到请求头order_headers里面传递给
Request对象的参数headers赋值,调用urllib.request.urlopen()就能带上Cookie会话信息请求了,虽然步骤挺多,不过方法还是行得通的。
Python爬虫基础之Cookie的更多相关文章
- Python爬虫基础
前言 Python非常适合用来开发网页爬虫,理由如下: 1.抓取网页本身的接口 相比与其他静态编程语言,如java,c#,c++,python抓取网页文档的接口更简洁:相比其他动态脚本语言,如perl ...
- python爬虫-基础入门-python爬虫突破封锁
python爬虫-基础入门-python爬虫突破封锁 >> 相关概念 >> request概念:是从客户端向服务器发出请求,包括用户提交的信息及客户端的一些信息.客户端可通过H ...
- python爬虫-基础入门-爬取整个网站《3》
python爬虫-基础入门-爬取整个网站<3> 描述: 前两章粗略的讲述了python2.python3爬取整个网站,这章节简单的记录一下python2.python3的区别 python ...
- python爬虫-基础入门-爬取整个网站《2》
python爬虫-基础入门-爬取整个网站<2> 描述: 开场白已在<python爬虫-基础入门-爬取整个网站<1>>中描述过了,这里不在描述,只附上 python3 ...
- python爬虫-基础入门-爬取整个网站《1》
python爬虫-基础入门-爬取整个网站<1> 描述: 使用环境:python2.7.15 ,开发工具:pycharm,现爬取一个网站页面(http://www.baidu.com)所有数 ...
- Python爬虫基础(一)——HTTP
前言 因特网联系的是世界各地的计算机(通过电缆),万维网联系的是网上的各种各样资源(通过超文本链接),如静态的HTML文件,动态的软件程序······.由于万维网的存在,处于因特网中的每台计算机可以很 ...
- 【学习笔记】第二章 python安全编程基础---python爬虫基础(urllib)
一.爬虫基础 1.爬虫概念 网络爬虫(又称为网页蜘蛛),是一种按照一定的规则,自动地抓取万维网信息的程序或脚本.用爬虫最大的好出是批量且自动化得获取和处理信息.对于宏观或微观的情况都可以多一个侧面去了 ...
- Python爬虫基础之requests
一.随时随地爬取一个网页下来 怎么爬取网页?对网站开发了解的都知道,浏览器访问Url向服务器发送请求,服务器响应浏览器请求并返回一堆HTML信息,其中包括html标签,css样式,js脚本等.我们之前 ...
- Python爬虫基础之认识爬虫
一.前言 爬虫Spider什么的,老早就听别人说过,感觉挺高大上的东西,爬网页,爬链接~~~dos黑屏的数据刷刷刷不断地往上冒,看着就爽,漂亮的校花照片,音乐网站的歌曲,笑话.段子应有尽有,全部都过来 ...
随机推荐
- (二)jdk8学习心得之Lambda表达式
二.Lambda表达式 1. 格式 (参数1,参数2,…,参数n)->{方法体} 注意: (参数1,参数2,...,参数n)要与方法接口中的参数一致,但是名字可以不一样. 此外,方法类型接口,有 ...
- Python之常用第三方库总结
在使用python进行开发的时候,经常我们需要借助一些第三方库,进行日常代码的开发工作.这里总结一些常用的类库 1. requests Requests 是用Python语言编写,基于 urllib, ...
- Keil MDK5的ITM调试
https://blog.csdn.net/burgesskzg/article/details/77100453
- 管理者的情商EQ
管理者的情商EQ1 IQ与EQ与AQ: IQ:智慧.逻辑.解决问题 EQ:情感商数.领导团队的热情.互动 AQ:逆商.碰到逆境怎么办.得重大疾病怎么办 成功者的概率: 放弃者:70% 半途而废者:25 ...
- LODOP打印用JS获取的当前日期
该文详细一步步解释JS获取当前时间的方法,新手小白也看到懂,最后是实际的获取当前年月份的方法.JS中的Date()对象,包含很多当前系统时间的方法,首先建立一个Date()对象,这里取名为date,然 ...
- codeforces675D
Tree Construction CodeForces - 675D During the programming classes Vasya was assigned a difficult pr ...
- 北京2018网络赛A题
题意:给你一个迷宫,迷宫有开始节点和结束节点,问你从开始走到结束的最小时间,其中,#代表这个点有毒气,身上必须带着氧气瓶才行,B代表每次进入这个点可以带一个氧气瓶,最多身上带五个,P代表进入这个点加速 ...
- Nginx PRECONTENT mirror模块
L62 location = /mirror { internal ; //只能内部访问 proxy_pass http://sho***.com.cn:8011$request_uri; proxy ...
- 小米Play获取ROOT权限的经验
小米Play通过什么方式开通了Root权限?大家知道,android机器有Root权限,一旦手机开通了root相关权限,就能够实现更多的功能,举个栗子大家企业的营销部门,使用一些营销应用都需要在Roo ...
- input密码框输入后设置显示为星号或其他样式
预览效果 核心代码 <div class="text-input" :class="right?'textinput-right':''"> < ...