Cookie
为什么要使用Cookie呢?
Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)
比如说有些网站需要登录后才能访问某个页面,在登录之前,你想抓取某个页面内容是不允许的。那么我们可以利用Urllib库保存我们登录的Cookie,然后再抓取其他页面就达到目的了
煮个栗子:
from urllib.request import Request, urlopen
# 比如有一个用户个人中心页面(必须要用户登录后才能访问)
url = "http://www.xxx.cn/index/user.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36",
"Cookie": "UM_distinctid=160012e864467c-0ac5f23391c2a2-1781c36-13c680-160012e86452f2; 53gid2=10301246171008; 53revisit=1511848315000; 53gid1=10301246171008; acw_tc=AQAAAEjeF1UEWgcAhfEOfJcfh7DKEoGu; CNZZDATA1261969808=1339833116-1511844320-http%253A%252F%252Fbbs.bjsxt.com%252F%7C1525846111; PHPSESSID=23llahql70p4trc6nm15gid8g4; visitor_type=old; 53gid0=10301246171008; 53kf_72085067_keyword=; kf_72085067_keyword_ok=1; 53kf_72085067_land_page=http%253A%252F%252Fwww.sxt.cn%252F; kf_72085067_land_page_ok=1"
}
req = Request(url, headers=headers)
resp = urlopen(req)
info = resp.read()
print(info.decode())
可以看的出来,只需要在headers中增加cookie就可以了,但是这样很麻烦,每次都要从网站上找到cookie然后手动复制到代码中增加cookie,显然很low的一种做法,于是有了下面自动获取cookie的做法:
案例1:获取Cookie保存到变量
from urllib.request import HTTPCookieProcessor
from urllib.request import build_opener
from urllib.request import Request
from http.cookiejar import CookieJar
from urllib.parse import urlencode
#声明一个CookieJar对象实例来保存cookie
cookie = CookieJar()
#利用HTTPCookieProcessor对象来创建cookie处理器
cookiePro = HTTPCookieProcessor(cookie)
#通过handler来构建opener
opener = build_opener(cookiePro)
login_url = "http://www.xxx.cn/index/login/login"
header = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36"}
fromdata = {
"user": "xxx",
"password": "***"
}
data = urlencode(fromdata).encode()
request = Request(login_url, headers=header, data=data)
response = opener.open(request)
info_url = 'http://www.xxx.cn/index/user.html'
request_info = Request(info_url)
response = opener.open(request_info)
html = response.read()
print(html.decode())
这里有两个要点:
一:Opener
当你获取一个URL你使用一个opener(一个urllib.OpenerDirector的实例)。在前面,我们都是使用的默认的opener,也就是urlopen。它是一个特殊的opener,可以理解成opener的一个特殊实例,传入的参数仅仅是url,data,timeout。
如果我们需要用到Cookie,只用这个opener是不能达到目的的,因为自带的urlopener根本不会保存cookie所以我们需要创建更一般的opener来实现对Cookie的设置
二:Cookielib
cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib模块配合使用来访问Internet资源。Cookielib模块非常强大,我们可以利用本模块的CookieJar类的对象来捕获cookie并在后续连接请求时重新发送,比如可以实现模拟登录功能。该模块主要的对象有CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar
案例2:cookie保存文件的读取
from urllib.request import build_opener, Request
from urllib.request import HTTPCookieProcessor
from http.cookiejar import MozillaCookieJar
from urllib.parse import urlencode
def get_cookie():
# 请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"}
login_url = "http://www.xxx.cn/index/login/login.html"
form_data = {
"user": "xxx",
"password": "****"
}
# 转换编码
f_data = urlencode(form_data)
req = Request(login_url, headers=headers, data=f_data.encode())
# 创建保存可以序列化cookie的文件对象
cookie = MozillaCookieJar("cookie.txt")
# 构造可保存cookie的控制器
c_handler = HTTPCookieProcessor(cookie)
# 构造opener
opener = build_opener(c_handler)
# 发送请求 -- 登录成功 (用户名和密码 正确)
opener.open(req)
cookie.save(ignore_discard=True, ignore_expires=True)
def use_cookie():
# 请求头
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"}
info_url = "http://www.xxx.cn/index/user.html"
# 创建保存可以序列化cookie的文件对象
cookie = MozillaCookieJar()
# 加载cookie文件
cookie.load("cookie.txt", ignore_discard=True, ignore_expires=True)
# 构造可保存cookie的控制器
c_handler = HTTPCookieProcessor(cookie)
# 构造opener
opener = build_opener(c_handler)
# 构造访问个人页面请求
req1 = Request(info_url, headers=headers)
# 发送请求
resp2 = opener.open(req1)
# 打印信息
print(resp2.read().decode())
if __name__ == '__main__':
# get_cookie()
use_cookie()
URLError
首先解释下URLError可能产生的原因:
- 网络无连接,即本机无法上网
- 连接不到特定的服务器
- 服务器不存在
在代码中,我们需要用try-except语句来包围并捕获相应的异常,代码如下:
from urllib.request import Request, urlopen
from urllib.error import URLError
url = "http://www.xxxxx.cn/index/us3er.html"
try:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36"
}
req = Request(url, headers=headers)
resp = urlopen(url, timeout=1)
print(resp.read().decode())
except URLError as e:
if len(e.args) == 0:
print(e.code)
else:
print(e.args[0])
print("获取数据完毕")
我们利用了 urlopen方法访问了一个不存在的网址,运行结果如下:
[Errno 11004] getaddrinfo failed