选票造假?使用文本验证码能反制爬虫程序吗?有什么问题?

投票程序

我们经常见到这样一种情况:在某个投票竞选活动中,允许任何人参与投票,当你进行一次点击以后,竞选者就会得到一票,最后统计谁的票数更多。

毫无疑问,如果没有任何防护措施,单纯统计点击次数的话,那么简单的爬虫程序就能够进行“刷票”了。为了避免这种情况,一个常见的方式,可能是要求输入文本验证码。例如,在大多数网站进行登录的时候,要求输入文本验证码,才能完成一次登陆尝试,目的就是为了限制程序批量请求,防止“弱口令爆破”的问题。

但是,是否有了文本验证码就真的能防止“刷票”,解决问题了呢?

添加验证码保护

创建验证码

在python中,一个非常容易的生成验证码的方法,是直接安装验证码库:pip install captcha

使用代码绘制一个验证码

from captcha.image import ImageCaptcha


image = ImageCaptcha(width=250, height=100)

captcha_text = "sagegrass"

image.generate(captcha_text)
image.write(captcha_text, "sagegrass.png")

现在,我们就得到了一个验证码:

绘制一个随机的验证码

 

import random
import string
import os

from captcha.image import ImageCaptcha

def generate_captcha(file_path="captcha_images", length=4):
    chars = string.ascii_letters + string.digits
    random_string = "".join(random.choice(chars) for _ in range(length))
    image = ImageCaptcha(width=250, height=100)
    image.generate(random_string)
    if not os.path.exists(file_path):
        os.mkdir(file_path)
    image.write(random_string, os.path.join(file_path, f"{random_string}.png"))


generate_captcha()

设计投票页面

下面,我们将模拟一个简单的投票页面,以还原投票程序

创建app.py

import random
import string
import os

from flask import Flask, render_template, request, session, redirect, url_for
from captcha.image import ImageCaptcha


app = Flask(__name__)
app.secret_key = "secret_key"


votes = {"baby1": 0, "baby2": 0}


def generate_captcha(file_path="captcha_images", length=4):
    chars = string.ascii_letters + string.digits
    random_string = "".join(random.choice(chars) for _ in range(length))
    image = ImageCaptcha(width=250, height=100)
    file_path = os.path.join("static", file_path)
    if not os.path.exists(file_path):
        os.makedirs(file_path)

    captcha_path = os.path.join(file_path, f"{random_string}.png")
    image.write(random_string, captcha_path)

    session["captcha"] = random_string

    return captcha_path


@app.route("/", methods=["GET", "POST"])
def vote():
    if request.method == "GET":
        captcha_path = generate_captcha()
        return render_template("vote.html", votes=votes, voted=False, captcha_path=captcha_path)

    if request.method == "POST":
        selected_baby = request.form.get("baby")
        e
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值