Error: File could not be downloaded from url: 2Cpatcha Api

Question:

I am trying to solve normal captcha using 2Captcha python API, but it gives error that file could not be downloaded. I dont know why is this happening, as I can download it manually from browser and do save as .png to download it. The below is the code

import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from twocaptcha import TwoCaptcha


solver = TwoCaptcha(apikey)

try:
    result = solver.normal('https://v2.gcchmc.org/captcha/image/aa699f305917812978c911e87ab126a782f726e7/')

except Exception as e:
    sys.exit(e)

else:
    sys.exit('solved: ' + str(result))

I also tried to download the file using requests and then give it to the API but that also shows error. The code for requests is

url = 'https://v2.gcchmc.org/captcha/image/aa699f305917812978c911e87ab126a782f726e7/'
import requests
from PIL import Image
from io import BytesIO
response = requests.get(url)
img = Image.open(BytesIO(response.content))   # error occurs here
img.save('output.png')

The Error is

raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x00000141224AB2C0>

If anyone can help me download the image using script I will be thankful. The captcha is showed on the following url:
https://v2.gcchmc.org/book-appointment/

Asked By: farhan jatt

||

Answers:

Your code is fine and it is the problem caused by headers. The url expects headers from you and you are not providing headers. This causes error response which the PIL library can not understand.
The working code will be

url = 'https://v2.gcchmc.org/captcha/image/aa699f305917812978c911e87ab126a782f726e7/'
import requests
from PIL import Image
from io import BytesIO
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language': 'en-US,en;q=0.5',
    # 'Accept-Encoding': 'gzip, deflate, br',
    'DNT': '1',
    'Connection': 'keep-alive',
    'Upgrade-Insecure-Requests': '1',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'none',
    'Sec-Fetch-User': '?1',
}
response = requests.get(url, headers)
img = Image.open(BytesIO(response.content))   # error occurs here
img.save('output.png')
Answered By: Farhan Ahmed