一、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的更多相关文章

  1. Python爬虫基础

    前言 Python非常适合用来开发网页爬虫,理由如下: 1.抓取网页本身的接口 相比与其他静态编程语言,如java,c#,c++,python抓取网页文档的接口更简洁:相比其他动态脚本语言,如perl ...

  2. python爬虫-基础入门-python爬虫突破封锁

    python爬虫-基础入门-python爬虫突破封锁 >> 相关概念 >> request概念:是从客户端向服务器发出请求,包括用户提交的信息及客户端的一些信息.客户端可通过H ...

  3. python爬虫-基础入门-爬取整个网站《3》

    python爬虫-基础入门-爬取整个网站<3> 描述: 前两章粗略的讲述了python2.python3爬取整个网站,这章节简单的记录一下python2.python3的区别 python ...

  4. python爬虫-基础入门-爬取整个网站《2》

    python爬虫-基础入门-爬取整个网站<2> 描述: 开场白已在<python爬虫-基础入门-爬取整个网站<1>>中描述过了,这里不在描述,只附上 python3 ...

  5. python爬虫-基础入门-爬取整个网站《1》

    python爬虫-基础入门-爬取整个网站<1> 描述: 使用环境:python2.7.15 ,开发工具:pycharm,现爬取一个网站页面(http://www.baidu.com)所有数 ...

  6. Python爬虫基础(一)——HTTP

    前言 因特网联系的是世界各地的计算机(通过电缆),万维网联系的是网上的各种各样资源(通过超文本链接),如静态的HTML文件,动态的软件程序······.由于万维网的存在,处于因特网中的每台计算机可以很 ...

  7. 【学习笔记】第二章 python安全编程基础---python爬虫基础(urllib)

    一.爬虫基础 1.爬虫概念 网络爬虫(又称为网页蜘蛛),是一种按照一定的规则,自动地抓取万维网信息的程序或脚本.用爬虫最大的好出是批量且自动化得获取和处理信息.对于宏观或微观的情况都可以多一个侧面去了 ...

  8. Python爬虫基础之requests

    一.随时随地爬取一个网页下来 怎么爬取网页?对网站开发了解的都知道,浏览器访问Url向服务器发送请求,服务器响应浏览器请求并返回一堆HTML信息,其中包括html标签,css样式,js脚本等.我们之前 ...

  9. Python爬虫基础之认识爬虫

    一.前言 爬虫Spider什么的,老早就听别人说过,感觉挺高大上的东西,爬网页,爬链接~~~dos黑屏的数据刷刷刷不断地往上冒,看着就爽,漂亮的校花照片,音乐网站的歌曲,笑话.段子应有尽有,全部都过来 ...

随机推荐

  1. SSM项目整合Quartz

    一.背景 SSM项目中要用到定时器,初期使用Timer,后来用spring 的schedule,都比较简单,所以功能比较单一而且他们不能动态的配置时间.后来就研究quartz,准备整合到项目中.Qua ...

  2. 关于Oracle使用管理员账号登录失败的问题

    我在本地建的Oracle数据库在调试自己写的存储过程的时候提示缺少 debug connect session 权限,一般情况下根据这个提示直接用管理员账号登录进去,执行 grant debug co ...

  3. 利用ir.sequence自动生成序列号

    利用ir.sequence自动生成序列号 什么是序列号 可以这么理解,我有一个产品序号,编码的前缀是SOP,后缀是0001~9999的序号,没生成一个产品就自动流水加一,序列号不会重复,odoo中的i ...

  4. P1744 采购特价商品

    原题链接 https://www.luogu.org/problemnew/show/P1744 一道最短路的模板题.....很简单吧 求最短路的方法有很多,但是对于刚学完Floyd的我,只会用这个. ...

  5. 【UOJ453】【集训队作业2018】围绕着我们的圆环 线性基 DP

    题目大意 有一个 \(n\times k\) 的 01矩阵 \(C\),求有多少个 \(n\times m\) 的矩阵 \(A\) 和 \(m\times k\) 的矩阵 \(B\),满足 \(A\t ...

  6. docker报错:Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

    在github上开到这样一条 于是 这两个选项换着来 具体怎么回事,咱也不知道,咱也不敢问 改完后蹭蹭的

  7. CodeForces - 597C Subsequences (树状数组+动态规划)

    For the given sequence with n different elements find the number of increasing subsequences with k + ...

  8. 商务电话思维图(XMind für Geschäftliche Telefongespräche)

    在和德国人打交道时,经常会遇到打电话的情景,应该怎么应对呢?不用担心,记住下面这个导图,轻松搞定德语电话的常用句型. 最后,按照惯例,来张美景.人越是上了年纪,就活的越是小心.但无论外界怎么样,请保持 ...

  9. jquery-防多店铺购物车结算全选,单选,及删除,价格计算

    <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...

  10. Centos6安装Percona-tools工具

    Centos6安装Percona-tools工具 环境:centos6.x yum -y install perl-DBI yum -y install perl-DBD-MySQL yum -y i ...