隨著網絡技術的不斷發展和應用,驗證碼(CAPTCHA)成為了互聯網中防止惡意程序或者不法分子對計算機或網絡的攻擊和破解的重要手段。在Python中,驗證碼的類型也有很多種,下面我們就來一一介紹。
1. 圖像驗證碼
import random from PIL import Image, ImageDraw, ImageFont # 生成隨機驗證碼 def random_char(): return chr(random.randint(65, 90)) # 生成隨機顏色 def random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 生成驗證碼圖片 def create_image(checkcode): width, height = 240, 60 im = Image.new('RGB', (width, height), 'white') draw = ImageDraw.Draw(im) # 設置字體 font = ImageFont.truetype('arial.ttf', 40) # 繪制每個字符 for i in range(4): draw.text((60 * i + 10, 10), checkcode[i], font=font, fill=random_color()) # 繪制干擾線 for i in range(10): draw.line((random.randint(0, width), random.randint(0, height), random.randint(0, width), random.randint(0, height)), fill=random_color()) # 繪制點 for i in range(50): draw.point((random.randint(0, width), random.randint(0, height)), fill=random_color()) # 保存圖片 im.save('checkcode.png') checkcode = ''.join([random_char() for i in range(4)]) create_image(checkcode)
2. 數學公式驗證碼
import random import os # 生成數學公式驗證碼 def create_math_code(): num1 = random.randint(0, 10) num2 = random.randint(0, 10) operator = random.choice(['+', '-', '*']) exp = f'{num1} {operator} {num2} = ?' ans = eval(f'{num1} {operator} {num2}') return exp, ans # 保存驗證碼 def save_image(exp): os.system(f'echo "{exp[0]}" | convert -background white -size 200x100 -font Arial -bordercolor white -border 10 -pointsize 36 -density 150 text:- math.png') exp, ans = create_math_code() save_image(exp)
3. 滑動拼圖驗證碼
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Chrome() driver.get('https://www.antfin.com/') # 拖動滑塊 def drag_and_drop(): slider_element = driver.find_element_by_css_selector('.nc_iconfont.btn_slide') ActionChains(driver).click_and_hold(slider_element).perform() for i in range(10): ActionChains(driver).move_by_offset(10, 0).perform() ActionChains(driver).release().perform() drag_and_drop()
以上就是Python中幾種常見的驗證碼類型。可以根據實際需求選擇相應的類型,提高用戶的安全性和使用體驗。