wohnbot/handlers/gesobau_handler.py

128 lines
5.8 KiB
Python
Raw Normal View History

2025-12-27 11:59:04 +01:00
from .base_handler import BaseHandler
import logging
import asyncio
logger = logging.getLogger(__name__)
class GesobauHandler(BaseHandler):
def __init__(self, browser_context):
self.context = browser_context
2025-12-27 11:59:04 +01:00
async def apply(self, listing: dict, result: dict) -> dict:
page = await self.context.new_page()
try:
2025-12-29 22:46:10 +01:00
logger.info(f"[GESOBAU] Opening page: {listing['link']}")
response = await page.goto(listing["link"], wait_until="networkidle")
logger.info("[GESOBAU] Page loaded")
2025-12-27 11:59:04 +01:00
await asyncio.sleep(2)
2025-12-29 22:46:10 +01:00
# 404 detection
status = response.status if response else None
page_title = await page.title()
if status == 404 or (page_title and "404" in page_title):
logger.warning(f"[GESOBAU] Listing is down (404): {listing['link']}")
result["success"] = False
result["message"] = "Listing is no longer available (404). Application impossible. Will not retry."
result["permanent_fail"] = True
await page.close()
return result
# Always handle cookies and consent before anything else
2025-12-27 11:59:04 +01:00
await self.handle_cookies(page)
await self.handle_consent(page)
# Save HTML after modal handling for debugging
try:
html_content = await page.content()
with open("data/gesobau_debug.html", "w", encoding="utf-8") as f:
f.write(html_content)
except Exception as e:
logger.debug(f"[GESOBAU] Debug HTML not saved: {e}")
# Tailored 404 detection: Angebot nicht mehr verfügbar
if "Angebot nicht mehr verfügbar" in html_content:
logger.warning("[GESOBAU] Permanent fail: Angebot nicht mehr verfügbar")
result["permanent_fail"] = True
result["message"] = "Listing is no longer available (Angebot nicht mehr verfügbar). Marked as permanent fail."
return result
2025-12-27 11:59:04 +01:00
# Look for application button
logger.info("[GESOBAU] Searching for application button...")
2025-12-27 11:59:04 +01:00
selectors = [
'a[href*="bewerben"]',
'button:has-text("Bewerben")',
'a:has-text("Bewerben")',
'button.btn',
2025-12-27 11:59:04 +01:00
]
apply_btn = None
for sel in selectors:
all_btns = await page.query_selector_all(sel)
logger.debug(f"[GESOBAU] Selector '{sel}': {len(all_btns)} matches")
2025-12-27 11:59:04 +01:00
for btn in all_btns:
try:
if await btn.is_visible():
apply_btn = btn
logger.info(f"[GESOBAU] Found visible application button: {sel}")
2025-12-27 11:59:04 +01:00
break
except Exception as e:
logger.debug(f"[GESOBAU] Button visibility error: {e}")
2025-12-27 11:59:04 +01:00
if apply_btn:
break
if apply_btn:
await apply_btn.scroll_into_view_if_needed()
await asyncio.sleep(0.5)
await apply_btn.click()
await asyncio.sleep(2)
2025-12-29 22:46:10 +01:00
# --- Post-click confirmation logic ---
logger.info("[GESOBAU] Clicked application button, checking for confirmation...")
# Save screenshot and HTML after click
try:
await page.screenshot(path="data/gesobau_after_apply.png")
logger.info("[GESOBAU] Saved screenshot after application click.")
except Exception as e:
logger.warning(f"[GESOBAU] Could not save screenshot: {e}")
try:
html_after = await page.content()
with open("data/gesobau_after_apply.html", "w", encoding="utf-8") as f:
f.write(html_after)
logger.info("[GESOBAU] Saved HTML after application click.")
except Exception as e:
logger.warning(f"[GESOBAU] Could not save HTML after apply: {e}")
# Look for confirmation message on the page
confirmation_selectors = [
'text="Vielen Dank"',
'text="Ihre Anfrage wurde gesendet"',
'text="Bestätigung"',
'div:has-text("Vielen Dank")',
'div:has-text("Ihre Anfrage wurde gesendet")',
]
confirmed = False
for sel in confirmation_selectors:
try:
el = await page.query_selector(sel)
if el and await el.is_visible():
logger.info(f"[GESOBAU] Found confirmation element: {sel}")
confirmed = True
break
except Exception as e:
logger.debug(f"[GESOBAU] Error checking confirmation selector {sel}: {e}")
if confirmed:
result["success"] = True
result["message"] = "Application submitted and confirmation detected."
else:
logger.warning("[GESOBAU] No confirmation message detected after application click.")
result["success"] = False
result["message"] = "Clicked application button, but no confirmation detected. Check screenshot and HTML."
2025-12-27 11:59:04 +01:00
else:
logger.warning("[GESOBAU] No application button found.")
2025-12-27 11:59:04 +01:00
result["message"] = "No application button found."
except Exception as e:
result["message"] = f"Error during application: {e}"
logger.error(f"[GESOBAU] Application error: {e}")
finally:
await page.close()
return result