模拟登录
模拟登录常用于大型数据爬取,通过模拟登录,获得网站发给用户有效的 cookies,在爬虫爬取数据时,可以增加网站对爬虫的信任度,从而达到更好的爬取效果。
准备
- Requests
- BeautifulSoup
- re
- cookielib
开始
模拟登录果壳
思路:
- 浏览器访问果壳登录页面,打开调试器,分析表单 html 元素(需要邮箱、密码、验证码三项)
- 分析验证码路径,构造 python 代码获取验证码
- 使用 requests 的 session() 方法,为每次请求建立关系 (http 为无状态)
- 用 BeautifulSoup 解析 requests 请求回来的页面,找到相应的 post 表单,分析并填写表单每一项
- 首次登录用 cookielib 保存网站为用户分配的 cookies
- 第一次登录成功后,之后采取 cookies 登录即可完成模拟登录
获取表单内容
浏览器打开调试器快捷键:ctrl+shift+c
, 在表单处随意填写,点击果壳网上的登录按钮:
查看调试器 Network
,查找到 sign_in/
用的是 POST
方法提交表单,且Form Data
如下:
表单说明 | |
---|---|
csrf_token | 防止XSS攻击的随机字符串 |
username | 用户名 |
password | 密码 |
captcha | 验证码 |
captcha_rand | 获取验证码的随机值 |
permanent | y(固定值) |
经过查看 html
源代码可以知道,csrf_token
、captcha_rand
都可以在页面找到:
从上往下依次是 csrf_token
、captcha_rand
、以及验证码地址
,观察验证码地址 https://account.guokr.com/captcha/1940664610/
, https://account.guokr.com/captcha/
是固定的,后面的数字部分是随机的,即 captcha_rand
,部分代码:
session = requests.session()
def get_csrf_captcha_rand(url):
response = session.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
csrf_token = soup.select('input#csrf_token')[0]
captcha_rand = soup.select('input#captchaRand')[0]
match_cs = re.findall(r'.*?value="(.*)".*', str(csrf_token))[0]
match_rand = re.findall(r'.*?value="(.*?)".*', str(captcha_rand))[0]
return match_cs, match_rand
代码注释:通过有连接的 session 请求果壳登录 url,用 BeautifulSoup 解析网页,获取 csrf_token、captcha_rand,然后返回。
获取验证码图片 (下载到本地并打开让用户输入)
通过字符串拼接 get_csrf_captcha_rand
方法返回的 captcha_rand
,得到https://account.guokr.com/captcha/1940664610/
,然而这串数字是随机的 10 位数,通常是以当前时间生成,代码:
def get_captcha(rand): # 保存captcha.png图片
import time
time = str(int(time.time() * 1000))
captcha_url = 'https://account.guokr.com/captcha/{}/?v={}'.format(rand, time)
response = session.get(captcha_url, headers=headers)
with open('captcha.png', 'wb') as f:
f.write(response.content)
f.close()
from PIL import Image
try:
captcha_image = Image.open('captcha.png')
captcha_image.show()
captcha_image.close()
except:
print 'captcha.png not found!'
code = raw_input('please check the captcha code and enter it:')
return code
代码注释:将当前时间转换成字符串,与验证码图片 url 拼接,访问该 url 后,将图片保存到本地并用 PIL 图片库展示给用户进行输入,最后再将用户的输入返回。
提交表单,获取 cookies
集齐上面的表单字段后,就可以正式登录:
def guokr_login(account, password): # 正式登录
url = 'https://account.guokr.com/sign_in/'
csrf_captcha_rand = get_csrf_captcha_rand(url)
post_data = {
'csrf_token': csrf_captcha_rand[0],
'username': account,
'password': password,
'captcha': get_captcha(csrf_captcha_rand[1]),
'captcha_rand': csrf_captcha_rand[1],
'permanent': 'y'
}
response = session.post(url, data=post_data, headers=headers)
session.cookies.save()
代码注释:拼凑表单,用 session 建立连接,最后保存 cookies 用作后面的登录, 这段代码最重要的是获取登录后的 cookies,以下是 cookies 内容:
从这段 cookies 文本来看,有效期大概为 1 个月。
判断 cookies 是否有效
拿到 cookies 后,要试一试 cookies 之后的登录是否有效,写一个判断登录是否有效的函数帮助判断,在浏览器中,找一个需要登录才能访问的 url:
def is_login(): # 判断是否为登录状态 http://www.guokr.com/i/0890827117/ allow_redirects=False
personal_url = 'http://www.guokr.com/user/feeds/'
response = session.get(personal_url, headers=headers)
if response.status_code != 200:
return False
else:
return True
代码注释:找一个需要登录状态才能访问的 url 访问,如果response.status_code
为 200
,则 cookies 有效,之后可以用此 cookies 访问果壳网,获取想要爬取的数据,但如果不行的话,就要再次调试。至这篇记录文章发表的时候,这种模拟登录的思路仍然有效,若果壳网站做了调整,则需要做出相应改变。
全部代码如下:
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
import cookielib
import re
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 UBrowser/6.1.3397.16 Safari/537.36',
}
session = requests.session()
session.cookies = cookielib.LWPCookieJar('cookies.txt')
try: # 尝试加载cookies
session.cookies.load(ignore_discard=True)
except:
print 'cookies failed to load!'
else:
print 'cookies has been loading!'
def get_csrf_captcha_rand(url): # 在页面中找到csrf_token和captcha_rand
response = session.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
csrf_token = soup.select('input#csrf_token')[0]
captcha_rand = soup.select('input#captchaRand')[0]
match_cs = re.findall(r'.*?value="(.*)".*', str(csrf_token))[0]
match_rand = re.findall(r'.*?value="(.*?)".*', str(captcha_rand))[0]
return match_cs, match_rand
def get_captcha(rand): # 保存captcha.png图片
import time
time = str(int(time.time() * 1000))
captcha_url = 'https://account.guokr.com/captcha/{}/?v={}'.format(rand, time)
response = session.get(captcha_url, headers=headers)
with open('captcha.png', 'wb') as f:
f.write(response.content)
f.close()
from PIL import Image
try:
captcha_image = Image.open('captcha.png')
captcha_image.show()
captcha_image.close()
except:
print 'captcha.png not found!'
code = raw_input('please check the captcha code and enter it:')
return code
def guokr_login(account, password): # 正式登录
url = 'https://account.guokr.com/sign_in/'
csrf_captcha_rand = get_csrf_captcha_rand(url)
post_data = {
'csrf_token': csrf_captcha_rand[0],
'username': account,
'password': password,
'captcha': get_captcha(csrf_captcha_rand[1]),
'captcha_rand': csrf_captcha_rand[1],
'permanent': 'y'
}
response = session.post(url, data=post_data, headers=headers)
session.cookies.save() # 保存cookies
def is_login(): # 判断是否为登录状态 http://www.guokr.com/i/0890827117/ allow_redirects=False
personal_url = 'http://www.guokr.com/user/feeds/'
response = session.get(personal_url, headers=headers)
if response.status_code != 200:
return False
else:
return True
guokr_login('账号', '密码')
is_login()
相关资料:
Requests:http://www.python-requests.org/en/master/
BeautifulSoup:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
Re 正则表达式:http://www.runoob.com/regexp/regexp-syntax.html