python爬虫之自动登录与验证码识别
作者:liuwons 时间:2022-05-18 07:22:53
在用爬虫爬取网站数据时,有些站点的一些关键数据的获取需要使用账号登录,这里可以使用requests发送登录请求,并用Session对象来自动处理相关Cookie。
另外在登录时,有些网站有时会要求输入验证码,比较简单的验证码可以直接用pytesser来识别,复杂的验证码可以依据相应的特征自己采集数据训练分类器。
以CSDN网站的登录为例,这里用Python的requests库与pytesser库写了一个登录函数。如果需要输入验证码,函数会首先下载验证码到本地,然后用pytesser识别验证码后登录,对于CSDN登录验证码,pytesser的识别率很高。
其中的pytesser的下载地址为: pytesser下载
具体代码如下:
#coding:utf-8
import sys
import time
import urllib
import shutil
import pytesser
import requests
from lxml import etree
config = {'gid': 1}
def parse(s, html, idx):
result = {}
tree = etree.HTML(html)
try:
result['lt'] = tree.xpath('//input[@name="lt"]/@value')[0]
result['execution'] = tree.xpath('//input[@name="execution"]/@value')[0]
result['path'] = tree.xpath('//form[@id="fm1"]/@action')[0]
except IndexError, e:
return None
valimg = None
valimgs = tree.xpath('//img[@id="yanzheng"]/@src')
if len(valimgs) > 0:
valimg = valimgs[0]
validateCode = None
if valimg:
fname = 'img/' + str(idx) + '_' + str(config['gid']) + '.jpg'
config['gid'] = config['gid'] + 1
ri = s.get("https://passport.csdn.net" + valimg)
with open(fname, 'wb') as f:
for chk in ri:
f.write(chk)
f.close()
validateCode = pytesser.image_file_to_string(fname)
validateCode = validateCode.strip()
validateCode = validateCode.replace(' ', '')
validateCode = validateCode.replace('\n', '')
result['validateCode'] = validateCode
return result
def login(usr, pwd, idx):
s = requests.Session()
r = s.get('https://passport.csdn.net/account/login',
headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0', 'Host': 'passport.csdn.net', })
while True:
res = parse(s, r.text, idx)
if res == None:
return False
url = 'https://passport.csdn.net' + res['path']
form = {'username': usr, 'password':pwd, '_eventId':'submit', 'execution':res['execution'], 'lt':res['lt'],}
if res.has_key('validateCode'):
form['validateCode'] = res['validateCode']
s.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',
'Accept-Language': 'zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'passport.csdn.net',
'Origin': 'https://passport.csdn.net',
'Referer': 'https://passport.csdn.net/account/login',
'Upgrade-Insecure-Requests': 1,
})
r = s.post(url, data=form)
tree = etree.HTML(r.text)
err_strs = tree.xpath('//span[@id="error-message"]/text()')
if len(err_strs) == 0:
return True
err_str = err_strs[0]
print err_str
err = err_str.encode('utf8')
validate_code_err = '验证码错误'
usr_pass_err = '帐户名或登录密码不正确,请重新输入'
try_later_err = '登录失败连续超过5次,请10分钟后再试'
if err[:5] == validate_code_err[:5]:
pass
elif err[:5] == usr_pass_err[:5]:
return False
elif err[:5] == try_later_err[:5]:
return False
else:
return True
if __name__ == '__main__':
main(sys.argv[1], sys.argv[2], 0)
来源:https://blog.csdn.net/tobacco5648/article/details/50640691
标签:python,自动登录,验证码
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
带你轻松接触MySQL数据库的出错代码列表
2008-12-31 15:06:00
Pandas过滤dataframe中包含特定字符串的数据方法
2021-10-11 13:39:08
![](https://img.aspxhome.com/file/2023/4/105274_0s.jpg)
将图片文件嵌入到wxpython代码中的实现方法
2023-04-23 06:52:20
![](https://img.aspxhome.com/file/2023/0/107230_0s.png)
python如何实时获取tcpdump输出
2021-05-05 14:41:36
python实现中文分词FMM算法实例
2022-07-31 18:40:55
ORACLE LATERAL-SQL-INJECTION 个人见解
2009-03-04 10:34:00
Django1.11自带分页器paginator的使用方法
2021-07-04 12:44:23
Python基于HOG+SVM/RF/DT等模型实现目标人行检测功能
2021-07-12 01:54:50
![](https://img.aspxhome.com/file/2023/2/105862_0s.jpg)
MySQL时间字段究竟使用INT还是DateTime
2010-03-09 14:46:00
开源MySQL公司停止提供企业版源代码tar包
2009-01-14 13:02:00
Swoole webSocket客服IM消息系统方案解析
2023-06-14 20:17:22
![](https://img.aspxhome.com/file/2023/7/55507_0s.png)
php在windows环境下获得cpu内存实时使用率(推荐)
2023-11-15 04:44:23
asp从Excel中筛选符合条件的记录保存至新的Excel中
2007-09-06 19:20:00
Django分页查询并返回jsons数据(中文乱码解决方法)
2022-12-02 22:44:20
Pandas提取单元格的值操作
2022-10-19 08:34:21
python 移动图片到另外一个文件夹的实例
2022-09-17 07:56:14
python中argparse模块基础及使用步骤
2023-01-26 19:21:59
Go语言指针用法详解
2023-08-05 17:06:36
![](https://img.aspxhome.com/file/2023/3/97153_0s.png)
Python字符串拼接的几种方法整理
2021-05-08 18:55:47
![](https://img.aspxhome.com/file/2023/5/64735_0s.jpg)
Case和If哪个更好用?
2009-10-28 18:25:00