Bu konuda, Python programlama dili ile web sitelerinden captcha resimlerini çekme ve pytesseract kütüphanesini kullanarak çözme işlemini anlatacağım. Captcha, web sitelerinde otomatik botların girişini önlemek için kullanılan bir güvenlik önlemidir. Bu örnek, bir HTTP oturumu kullanarak web sayfasından captcha resmini çeker, base64 kodunu çözer ve pytesseract ile metne dönüştürür.
1) Kütüphanelerin Koda Aktarılması
Python programlama dilinde kütüphaneleri içeri aktarmak için 'import' kodunu kullanırız.
Python:
import pytesseract, requests, base64
from bs4 import BeautifulSoup
from PIL import Image
2) İstek Atma
İstek atmak içinse 'requests' kütüphanesini kullanacağız.
Python:
session = requests.Session() # .Session yerine .get kullanabilirsiniz fakat cookie yönetmek için Session kullanmak daha kolaydır.
url = "http://localhost/Ders/index.php" # Captcha resminin olduğu URL
response = session.get(url) # GET ile istek gönderme
3) Resmi Açmak & Diğer İşlemler
Şimdi BeautifulSoup ile captcha image'yi alıyoruz ve resmi çözüyoruz.
Python:
soup = BeautifulSoup(response.text, "html.parser") # Kodları ayıklamak için html.parser kullanıyoruz.
base64_element = soup.find("img", {"id": "imgKod"}) # ID değeri imgKod olan img etiketini alıyoruz.
base64_code = base64_element["src"].split(",")[-1]
image_data = base64.b64decode(base64_code) # Resim base64 şeklinde olduğu için decode ediyoruz.
with open("decoded_image.png", "wb") as image_file: # decoded_image.png şeklinde kayıt ediyoruz.
image_file.write(image_data)
image = Image.open("decoded_image.png") # Burada pytesseract için resmi açıyoruz.
captcha_text = pytesseract.image_to_string(image) # image_to_string fonksiyonu ile resmi metine çeviriyoruz.
captcha_text = captcha_text.replace("\n", "").replace("\x0c", "").strip() # Özel karakter varsa temizlemesini söylüyoruz.
print(captcha_text) # Ekrana kodu yazdırıyoruz.
Kodun Tamamı:
Python:
import pytesseract
import requests
import base64
from bs4 import BeautifulSoup
from PIL import Image
session = requests.Session()
url = "http://localhost/Ders/index.php"
response = session.get(url)
soup = BeautifulSoup(response.text, "html.parser")
base64_element = soup.find("img", {"id": "imgKod"})
base64_code = base64_element["src"].split(",")[-1]
image_data = base64.b64decode(base64_code)
with open("decoded_image.png", "wb") as image_file:
image_file.write(image_data)
image = Image.open("decoded_image.png")
captcha_text = pytesseract.image_to_string(image)
captcha_text = captcha_text.replace("\n", "").replace("\x0c", "").strip()
print(captcha_text)