V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
whamjane
V2EX  ›  Python

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

  •  
  •   whamjane · 2016-01-20 18:34:25 +08:00 · 3251 次点击
    这是一个创建于 3026 天前的主题,其中的信息可能已经有所发展或是发生改变。
    高工们,请问如下代码中,获取 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!"
    3 条回复    2016-01-20 21:37:56 +08:00
    JoeShu
        1
    JoeShu  
       2016-01-20 18:41:17 +08:00
    得不到验证码,需要人工输入
    CheungKe
        2
    CheungKe  
       2016-01-20 19:22:07 +08:00
    urllib.urlretrieve(captchaAddr,"captcha.jpg")

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

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

    然后输入
    whamjane
        3
    whamjane  
    OP
       2016-01-20 21:37:56 +08:00
    @CheungKe @JoeShu 谢谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1202 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 17:36 · PVG 01:36 · LAX 10:36 · JFK 13:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.