爬虫 - Cookie 介绍 和 request使用
Cookie 介绍
1. Cookie
为什么要使用Cookie呢?
Cookie,指某些网站为了辨别用户身份、进行session跟踪而储存在用户本地终端上的数据(通常经过加密)
比如说有些网站需要登录后才能访问某个页面,在登录之前,你想抓取某个页面内容是不允许的。那么我们可以利用Urllib库保存我们登录的Cookie,然后再抓取其他页面就达到目的了。
1.1 Opener
当你获取一个URL你使用一个opener(一个urllib.OpenerDirector的实例)。在前面,我们都是使用的默认的opener,也就是urlopen。它是一个特殊的opener,可以理解成opener的一个特殊实例,传入的参数仅仅是url,data,timeout。
如果我们需要用到Cookie,只用这个opener是不能达到目的的,所以我们需要创建更一般的opener来实现对Cookie的设置
1.2 Cookielib
cookielib模块的主要作用是提供可存储cookie的对象,以便于与urllib模块配合使用来访问Internet资源。Cookielib模块非常强大,我们可以利用本模块的CookieJar类的对象来捕获cookie并在后续连接请求时重新发送,比如可以实现模拟登录功能。该模块主要的对象有CookieJar、FileCookieJar、MozillaCookieJar、LWPCookieJar
案例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.sxt.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": "17703181473", "password": "123456" } data = urlencode(fromdata).encode() request = Request(login_url, headers=header, data=data) response = opener.open(request) info_url = 'http://www.sxt.cn/index/user.html' request_info = Request(info_url) response = opener.open(request_info) html = response.read() print(html.decode())复制代码
我们使用以上方法将cookie保存到变量中,然后打印出了cookie中的值,运行结果如下
以上程序的原理如下
创建一个带有cookie的opener,在访问登录的URL时,将登录后的cookie保存下来,然后利用这个cookie来访问其他网址。
案例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.sxt.cn/index/login/login.html" form_data = { "user": "17703181473", "password": "123456" } # 转换编码 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.sxt.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()复制代码
2. URLError
首先解释下URLError可能产生的原因:
网络无连接,即本机无法上网
连接不到特定的服务器
服务器不存在
在代码中,我们需要用try-except语句来包围并捕获相应的异常,代码如下:
from urllib.request import Request, urlopen from urllib.error import URLError url = "http://www.sx435334t.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复制代码
requests使用
1. 介绍
对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助。入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取。那么这一节来简单介绍一下 requests 库的基本用法
2. 安装
利用 pip 安装
pip install requests复制代码
3. 基本请求
req = requests.get("http://www.baidu.com") req = requests.post("http://www.baidu.com") req = requests.put("http://www.baidu.com") req = requests.delete("http://www.baidu.com") req = requests.head("http://www.baidu.com") req = requests.options("http://www.baidu.com")复制代码
3.1 get请求
参数是字典,我们也可以传递json类型的参数:
import requests url = "http://www.baidu.com/s" params = {'wd': '尚学堂'} response = requests.get(url, params=params) print(response.url) response.encoding = 'utf-8' html = response.text # print(html)复制代码
3.2 post请求
参数是字典,我们也可以传递json类型的参数:
url = "http://www.sxt.cn/index/login/login.html" formdata = { "user": "17703181473", "password": "123456" } response = requests.post(url, data=formdata) response.encoding = 'utf-8' html = response.text # print(html)复制代码
3.3 自定义请求头部
伪装请求头部是采集时经常用的,我们可以用这个方法来隐藏:
headers = {'User-Agent': 'python'} r = requests.get('http://www.zhidaow.com', headers = headers) print(r.request.headers['User-Agent'])复制代码
3.4 设置超时时间
可以通过timeout属性设置超时时间,一旦超过这个时间还没获得响应内容,就会提示错误
requests.get('http://github.com', timeout=0.001)复制代码
3.5 代理访问
采集时为避免被封IP,经常会使用代理。requests也有相应的proxies属性
import requests proxies = { "http": "http://10.10.1.10:3128", "https": "https://10.10.1.10:1080", } requests.get("http://www.zhidaow.com", proxies=proxies)复制代码
如果代理需要账户和密码,则需这样
proxies = { "http": "http://user:pass@10.10.1.10:3128/", }复制代码
3.6 session自动保存cookies
seesion的意思是保持一个会话,比如 登陆后继续操作(记录身份信息) 而requests是单次请求的请求,身份信息不会被记录
# 创建一个session对象 s = requests.Session() # 用session对象发出get请求,设置cookies s.get('http://httpbin.org/cookies/set/sessioncookie/123456789') 复制代码
3.7 ssl验证
# 禁用安全请求警告 requests.packages.urllib3.disable_warnings() resp = requests.get(url, verify=False, headers=headers)复制代码
4 获取响应信息
代码 | 含义 |
---|---|
resp.json() | 获取响应内容(以json字符串) |
resp.text | 获取响应内容 (以字符串) |
resp.content | 获取响应内容(以字节的方式) |
resp.headers | 获取响应头内容 |
resp.url | 获取访问地址 |
resp.encoding | 获取网页编码 |
resp.request.headers | 请求头内容 |
resp.cookie | 获取cookie |
作者:爱看书的阿东
链接:https://juejin.cn/post/7028132939590270989