我要python生成验证码并在html文件中可以验证的代码
时间: 2024-04-08 15:34:18 浏览: 14
以下是一个使用Python生成验证码并在HTML文件中验证的代码示例:
Python 代码(生成验证码):
```python
from PIL import Image, ImageDraw, ImageFont
import random
def generate_captcha():
captcha_code = ''
# 随机生成4个字符作为验证码
for _ in range(4):
captcha_code += random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
# 创建一个新的图像对象
captcha_image = Image.new('RGB', (200, 100), (255, 255, 255))
draw = ImageDraw.Draw(captcha_image)
# 设置字体和字体大小
font = ImageFont.truetype('Arial.ttf', 40)
# 在图像上绘制验证码
draw.text((40, 30), captcha_code, font=font, fill=(0, 0, 0))
# 添加干扰线
for _ in range(10):
x1 = random.randint(0, 200)
y1 = random.randint(0, 100)
x2 = random.randint(0, 200)
y2 = random.randint(0, 100)
draw.line((x1, y1, x2, y2), fill=(0, 0, 0))
# 保存图像为JPEG格式
captcha_image.save('captcha.jpg')
return captcha_code
captcha_code = generate_captcha()
print("生成的验证码:", captcha_code)
```
HTML 代码(验证码验证页面):
```html
<!DOCTYPE html>
<html>
<head>
<title>验证码验证</title>
</head>
<body>
<h1>请输入验证码:</h1>
<form action="verify_captcha.py" method="POST">
<input type="text" name="captcha_input">
<img src="captcha.jpg" alt="验证码">
<input type="submit" value="验证">
</form>
</body>
</html>
```
请注意,上述示例代码仅供参考,您可能需要根据您的实际需求进行适当的修改和调整。此外,还需要确保PIL库已安装在您的Python环境中。