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黑屏的数据刷刷刷不断地往上冒,看着就爽,漂亮的校花照片,音乐网站的歌曲,笑话.段子应有尽有,全部都过来 ...
随机推荐
- Python百题计划
一.基础篇 想要像类似执行shell脚本一样执行Python脚本,需要在py文件开头加上什么?KEY:#!/usr/bin/env python Python解释器在加载 .py 文件中的代码时,会对 ...
- celery 和 haystack
celery 是分布式异步框架 haystack 是全文检索 只能在Django中用. 一.什么是celery? ---->它是Python写的,所以只支持Python使用.但是消 ...
- MongoDB ODBC Driver for Data Integration with Power BI
This guide will walk you through connecting Microsoft Power BI to a MongoDB DataSet using our MongoD ...
- [wikichip]zen架构图
https://en.wikichip.org/wiki/amd/microarchitectures/zen https://en.wikichip.org/wiki/amd/microarchit ...
- KDJ计算公式
计算方法编辑KDJ的计算比较复杂,首先要计算周期(n日.n周等)的RSV值,即未成熟随机指标值,然后再计算K值.D值.J值等.以n日KDJ数值的计算为例,其计算公式为n日RSV=(Cn-Ln)/(Hn ...
- static_assert与assert
C++0x中引入了static_assert这个关键字,用来做编译期间的断言,因此叫做静态断言. 其语法:static_assert(常量表达式,提示字符串). 如果第一个参数常量表达式的值为fals ...
- JAVA helloworld!
idea创建java项目 https://jingyan.baidu.com/article/48b558e3f8f6637f39c09a44.html 本地文档运行 java helloworld ...
- Redis-Cluster操作命令大全
今天整理下redis-cluster操作命令 一.Cluster操作命令 CLUSTER INFO 打印集群的信息 CLUSTER NODES 列出集群当前已知的所有节点(node),以及这些节点的相 ...
- hadoop记录-如何换namenode机器
namenode机器磁盘IO负载持续承压,造成NAMENODE切换多次及访问异常. 1 初始化新机器1.1 在新器1.1.1.3部署hadoop软件(直接复制standby1.1.1.2节点)1.2 ...
- Elasticsearch 快速开始
Elasticsearch 是一个分布式的 RESTful 风格的搜索和数据分析引擎. 查询 : Elasticsearch 允许执行和合并多种类型的搜索 - 结构化.非结构化.地理位置.度量指标 - ...