python 获取图片验证码是什么原理?

2016-01-20 18:34:25 +08:00
 whamjane
高工们,请问如下代码中,获取 captcha 的验证码那一段,究竟发生了什么,能够的得到验证码?


import requests
from bs4 import BeautifulSoup
import urllib
import re

loginUrl = 'http://accounts.douban.com/login'
formData={
"redir":"http://movie.douban.com/mine?status=collect",
"form_email":username,
"form_password":password,
"login":u'登录'
}
headers = {"User-Agent":'Mozilla/5.0 (Windows NT 6.1)\
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'}
r = requests.post(loginUrl,data=formData,headers=headers)
page = r.text
#print r.url

'''''获取验证码图片'''
#利用 bs4 获取 captcha 地址
soup = BeautifulSoup(page,"html.parser")
captchaAddr = soup.find('img',id='captcha_image')['src']
#利用正则表达式获取 captcha 的 ID
reCaptchaID = r'<input type="hidden" name="captcha-id" value="(.*?)"/'
captchaID = re.findall(reCaptchaID,page)
#print captchaID
#保存到本地
urllib.urlretrieve(captchaAddr,"captcha.jpg")
captcha = raw_input('please input the captcha:')

formData['captcha-solution'] = captcha
formData['captcha-id'] = captchaID

r = requests.post(loginUrl,data=formData,headers=headers)
page = r.text
if r.url=='http://movie.douban.com/mine?status=collect':
print 'Login successfully!!!'
print '我看过的电影','-'*60
#获取看过的电影
soup = BeautifulSoup(page,"html.parser")
result = soup.findAll('li',attrs={"class":"title"})
#print result
for item in result:
print item.find('a').get_text()
else:
print "failed!"
3262 次点击
所在节点    Python
3 条回复
JoeShu
2016-01-20 18:41:17 +08:00
得不到验证码,需要人工输入
CheungKe
2016-01-20 19:22:07 +08:00
urllib.urlretrieve(captchaAddr,"captcha.jpg")

先获取到图片链接,保存后,自己打开看

captcha = raw_input('please input the captcha:')

然后输入
whamjane
2016-01-20 21:37:56 +08:00
@CheungKe @JoeShu 谢谢

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/252183

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX