0% found this document useful (0 votes)
5 views4 pages

Selenium

The document is a Python script that automates the process of filling out an embassy appointment form using Selenium and Firefox. It includes functionalities for navigating to the form, accepting cookies, filling in personal information, handling captcha, and submitting the form. The script is designed to log actions and handle exceptions during the automation process.

Uploaded by

xelawu4902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views4 pages

Selenium

The document is a Python script that automates the process of filling out an embassy appointment form using Selenium and Firefox. It includes functionalities for navigating to the form, accepting cookies, filling in personal information, handling captcha, and submitting the form. The script is designed to log actions and handle exceptions during the automation process.

Uploaded by

xelawu4902
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

from selenium import webdriver

from selenium.webdriver.firefox.service import Service


from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import pytesseract
from PIL import Image
import io
import time
import logging

class EmbassyFormAutomation:
def __init__(self, gecko_path=None):
"""Initialize Firefox automation"""
# Set up Firefox options
firefox_options = Options()
# firefox_options.add_argument('--headless') # Uncomment to run in
headless mode

# Initialize Firefox driver


if gecko_path:
service = Service(gecko_path)
self.driver = webdriver.Firefox(service=service,
options=firefox_options)
else:
self.driver = webdriver.Firefox(options=firefox_options)

self.wait = WebDriverWait(self.driver, 10)

# Configure logging
logging.basicConfig(level=logging.INFO)
self.logger = logging.getLogger(__name__)

def navigate_to_form(self):
"""Navigate to the embassy appointment form"""
url = "https://service2.diplo.de/rktermin/extern/appointment_showForm.do?
locationCode=isla&realmId=108&categoryId=1600"
self.driver.get(url)
time.sleep(3) # Wait for page load

def accept_cookies(self):
"""Handle cookie consent if present"""
try:
cookie_button = self.wait.until(EC.presence_of_element_located(
(By.CSS_SELECTOR, "button[data-cookie-consent-accept]")))
cookie_button.click()
self.logger.info("Accepted cookies")
except TimeoutException:
self.logger.info("No cookie consent found")
pass

def fill_application_form(self, form_data):


"""Fill the embassy appointment form"""
try:
# Wait for form to be present
self.wait.until(EC.presence_of_element_located((By.TAG_NAME, "form")))
# Fill personal information
self.fill_field("familyName", form_data.get("familyName"))
self.fill_field("firstName", form_data.get("firstName"))
self.fill_field("email", form_data.get("email"))
self.fill_field("emailRepeat", form_data.get("email")) # Confirm email

# Handle date fields if present


if "dateOfBirth" in form_data:
self.fill_date("dateOfBirth", form_data["dateOfBirth"])

# Handle dropdown selections


if "nationality" in form_data:
self.select_dropdown("nationality", form_data["nationality"])

# Handle number of people if present


if "numberOfPersons" in form_data:
self.fill_field("numberOfPersons", form_data["numberOfPersons"])

# Handle captcha
self.handle_captcha()

# Check privacy policy checkbox if present


try:
checkbox = self.driver.find_element(By.NAME, "dataPrivacy")
if not checkbox.is_selected():
checkbox.click()
except NoSuchElementException:
self.logger.info("No privacy checkbox found")

# Submit form
self.submit_form()

return True

except Exception as e:
self.logger.error(f"Error filling form: {str(e)}")
return False

def fill_field(self, field_name, value):


"""Fill a text input field"""
try:
field = self.wait.until(EC.presence_of_element_located((By.NAME,
field_name)))
field.clear()
field.send_keys(value)
time.sleep(0.5) # Small delay between inputs
except Exception as e:
self.logger.error(f"Error filling field {field_name}: {str(e)}")

def fill_date(self, field_name, date_value):


"""Fill a date field"""
try:
date_field = self.wait.until(EC.presence_of_element_located((By.NAME,
field_name)))
date_field.clear()
date_field.send_keys(date_value)
except Exception as e:
self.logger.error(f"Error filling date field {field_name}: {str(e)}")
def select_dropdown(self, field_name, value):
"""Select value from dropdown"""
try:
dropdown =
Select(self.wait.until(EC.presence_of_element_located((By.NAME, field_name))))
dropdown.select_by_visible_text(value)
except Exception as e:
self.logger.error(f"Error selecting from dropdown {field_name}:
{str(e)}")

def handle_captcha(self):
"""Handle the captcha on the form"""
try:
# Find captcha image
captcha_img = self.wait.until(EC.presence_of_element_located(
(By.CSS_SELECTOR, "img[src*='captcha']")))

# Take screenshot of captcha


captcha_screenshot = captcha_img.screenshot_as_png
image = Image.open(io.BytesIO(captcha_screenshot))

# Process image for better OCR


image = image.convert('L') # Convert to grayscale

# Extract text
captcha_text = pytesseract.image_to_string(image)
captcha_text = ''.join(e for e in captcha_text if e.isalnum())

# Find and fill captcha input


captcha_input = self.driver.find_element(By.NAME, "captchaText")
captcha_input.clear()
captcha_input.send_keys(captcha_text)

self.logger.info("Captcha handled")

except Exception as e:
self.logger.error(f"Error handling captcha: {str(e)}")

def submit_form(self):
"""Submit the form"""
try:
submit_button = self.wait.until(EC.element_to_be_clickable(
(By.CSS_SELECTOR, "input[type='submit']")))
submit_button.click()
time.sleep(2) # Wait for submission
self.logger.info("Form submitted")
except Exception as e:
self.logger.error(f"Error submitting form: {str(e)}")

def close(self):
"""Close the browser"""
self.driver.quit()

def main():
# Example form data
form_data = {
"familyName": "Doe",
"firstName": "John",
"email": "[email protected]",
"dateOfBirth": "01.01.1990", # Format: DD.MM.YYYY
"nationality": "INDIA", # Exact text as it appears in dropdown
"numberOfPersons": "1"
}

try:
bot = EmbassyFormAutomation()
bot.navigate_to_form()
bot.accept_cookies()

success = bot.fill_application_form(form_data)
if success:
print("Form submitted successfully")
else:
print("Form submission failed")

except Exception as e:
print(f"Error: {str(e)}")

finally:
bot.close()

if __name__ == "__main__":
main()

You might also like