How To Generate Random Captcha In Python

Random captcha is very useful in web applications. It can be used to avoid network attacks. Python captcha module can help you to create both image and audio captcha easily. This article will show you how to create image and audio captcha file use the python captcha library.

1. Install Python Captcha Module.

  1. This module is not a python built-in module, you should install it before using it.
  2. Open a terminal and run the command pip install captcha to install it as below.
    192:~$ pip install captcha
    Collecting captcha
      Downloading (100kB)
        100% |████████████████████████████████| 102kB 453kB/s 
    Requirement already satisfied: Pillow in ./anaconda3/lib/python3.6/site-packages (from captcha) (5.1.0)
    Building wheels for collected packages: captcha
      Running bdist_wheel for captcha ... done
      Stored in directory: /Users/zhaosong/Library/Caches/pip/wheels/db/43/da/18c3613704085afd794b9efd2153ce104fdff5bab116633af8
    Successfully built captcha
    Installing collected packages: captcha
    Successfully installed captcha-0.2.4

2. Generate Image Captcha.

  1. After installing the Python captcha module successfully, follow the below steps to create an image captcha.
  2. Import captcha.image.ImageCaptcha class.
    from captcha.image import ImageCaptcha
  3. Create an instance of ImageCaptcha.
    image_captcha = ImageCaptcha()
  4. Call ImageCaptcha.generate_image method to create the image object.
    image = image_captcha.generate_image(captcha_text)
  5. If you want to add some noise curve or dots, you can call the create_noise_curve or create_noise_dots method.
  6. Call the method ImageCaptcha.write to save the image to a file.

3. Generate Audio Captcha.

  1. Before you can create an audio captcha, you should prepare some audio files, each file play one character pronounce, each pronounce’s file should be saved under a folder that has the character name.
  2. For example, if your text captcha is character abc, then you should have audio files such as a.wav, b.wav, and c.wav saved in “./voices/a/a.wav“, “./voices/b/b.wav“, “./voices/c/c.wav“.
  3. Then the audio captcha abc can be pronounced by playing each of the audio files in order. In the above example, the audio file root folder is “./voices”.
  4. Below are the audio captcha creation steps.
  5. Import class.
    from import AudioCaptcha
  6. Create an instance of AudioCaptcha, input the base audio pronounce files save folder. If you do not provide, it will use default digital pronounce only audio files.
    audio_captcha = AudioCaptcha(voicedir='./voices')
  7. Generate audio captcha data.

    audio_data = audio_captcha.generate(captcha_text)
  8. If you want to add white background noise, invoke the create_background_noise method.
  9. Save the audio captcha data into an audio file.

4. Python Image And Audio Captcha Example.

  1. This example will create both an image captcha and an audio captcha use the python captcha module.
  2. It will also use the Python matplotlib module to display the image in the matplotlib viewer.
  3. Below is the PyDev project source file list. You can read How To Run Python In Eclipse With PyDev to learn more.
  4. Below is the created image file and audio file.
  5. Image file text : nFTDaON9MG.
  6. Audio number: 8671787631, below is the audio file captcha.

5. Python Captcha Example Source Code.

    @author: zhaosong
    from captcha.image import ImageCaptcha
    from import AudioCaptcha
    import matplotlib.pyplot as plt
    import random
    # The number list, lower case character list and upper case character list are used to generate captcha text.
    number_list = ['0','1','2','3','4','5','6','7','8','9']
    alphabet_lowercase = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
    alphabet_uppercase = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
    # This function will create a random captcha string text based on above three list.
    # The input parameter is the captcha text length.
    def create_random_captcha_text(captcha_string_size=10):
        captcha_string_list = []
        base_char = alphabet_lowercase + alphabet_uppercase + number_list
        for i in range(captcha_string_size):
            # Select one character randomly.
            char = random.choice(base_char)
            # Append the character to the list.
        captcha_string = ''
        # Change the character list to string.    
        for item in captcha_string_list:
            captcha_string += str(item)
        return captcha_string
    # This function will create a fully digital captcha string text.
    def create_random_digital_text(captcha_string_size=10):
        captcha_string_list = []
        # Loop in the number list and return a digital captcha string list
        for i in range(captcha_string_size):
            char = random.choice(number_list)
        captcha_string = ''
        # Convert the digital list to string.    
        for item in captcha_string_list:
            captcha_string += str(item)
        return captcha_string
    # Create an image captcha with special text.
    def create_image_captcha(captcha_text):
        image_captcha = ImageCaptcha()
        # Create the captcha image.
        image = image_captcha.generate_image(captcha_text)
        # Add noise curve for the image.
        image_captcha.create_noise_curve(image, image.getcolors())
        # Add noise dots for the image.
        image_captcha.create_noise_dots(image, image.getcolors())
        # Save the image to a png file.
        image_file = "./captcha_"+captcha_text + ".png"
        image_captcha.write(captcha_text, image_file)
        # Display the image in a matplotlib viewer.
        print(image_file + " has been created.")
    # Create an audio captcha file.    
    def create_audio_captcha():
        # Create the audio captcha with the specified voice wav file library folder.
        # Each captcha char should has it's own directory under the specified folder ( such as ./voices),
        # for example ./voices/a/a.wav will be played when the character is a.
        # If you do not specify your own voice file library folder, the default built-in voice library which has only digital voice file will be used. 
        # audio_captcha = AudioCaptcha(voicedir='./voices')
        # Create an audio captcha which use digital voice file only.
        audio_captcha = AudioCaptcha()
        # Because we use the default module voice library, so we can only generate digital text voice.
        captcha_text = create_random_digital_text()
        # Generate the audio captcha file.
        audio_data = audio_captcha.generate(captcha_text)
        # Save the autiod captcha file.
        audio_file = "./captcha_"+captcha_text+'.wav'
        audio_captcha.write(captcha_text, audio_file)
        print(audio_file + " has been created.")
    if __name__ == '__main__':
        # Create random text.
        captcha_text = create_random_captcha_text()
        # Create image captcha.
        # Create audio captcha.

4 thoughts on “How To Generate Random Captcha In Python”

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.