隨著網(wǎng)絡(luò)技術(shù)的不斷發(fā)展和應(yīng)用,驗(yàn)證碼(CAPTCHA)成為了互聯(lián)網(wǎng)中防止惡意程序或者不法分子對(duì)計(jì)算機(jī)或網(wǎng)絡(luò)的攻擊和破解的重要手段。在Python中,驗(yàn)證碼的類(lèi)型也有很多種,下面我們就來(lái)一一介紹。
1. 圖像驗(yàn)證碼
import random from PIL import Image, ImageDraw, ImageFont # 生成隨機(jī)驗(yàn)證碼 def random_char(): return chr(random.randint(65, 90)) # 生成隨機(jī)顏色 def random_color(): return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) # 生成驗(yàn)證碼圖片 def create_image(checkcode): width, height = 240, 60 im = Image.new('RGB', (width, height), 'white') draw = ImageDraw.Draw(im) # 設(shè)置字體 font = ImageFont.truetype('arial.ttf', 40) # 繪制每個(gè)字符 for i in range(4): draw.text((60 * i + 10, 10), checkcode[i], font=font, fill=random_color()) # 繪制干擾線(xiàn) 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()) # 繪制點(diǎn) 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. 數(shù)學(xué)公式驗(yàn)證碼
import random import os # 生成數(shù)學(xué)公式驗(yàn)證碼 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 # 保存驗(yàn)證碼 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. 滑動(dòng)拼圖驗(yàn)證碼
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains driver = webdriver.Chrome() driver.get('https://www.antfin.com/') # 拖動(dòng)滑塊 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中幾種常見(jiàn)的驗(yàn)證碼類(lèi)型。可以根據(jù)實(shí)際需求選擇相應(yīng)的類(lèi)型,提高用戶(hù)的安全性和使用體驗(yàn)。