wohnbot/handlers/howoge_handler.py

81 lines
No EOL
3.3 KiB
Python

from .base_handler import BaseHandler
import logging
import asyncio
logger = logging.getLogger(__name__)
class HowogeHandler(BaseHandler):
def __init__(self, browser_context):
self.context = browser_context
async def apply(self, listing: dict, result: dict) -> dict:
page = await self.context.new_page()
try:
logger.info(f"[HOWOGE] Open: {listing['link']}")
response = await page.goto(listing["link"], wait_until="networkidle")
await asyncio.sleep(2)
# Detect 404 by status or page title
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"[HOWOGE] 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
return result
# Always handle cookies and consent before anything else
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/howoge_debug.html", "w", encoding="utf-8") as f:
f.write(html_content)
except Exception as e:
logger.debug(f"[HOWOGE] Debug HTML not saved: {e}")
await self.log_listing_details(listing)
logger.info("[HOWOGE] Searching for application button...")
selectors = [
'a[href*="besichtigung-vereinbaren"]',
'a:has-text("Besichtigung vereinbaren")',
'button:has-text("Besichtigung vereinbaren")',
'a:has-text("Anfragen")',
'button:has-text("Anfragen")'
]
apply_btn = None
for sel in selectors:
all_btns = await page.query_selector_all(sel)
logger.debug(f"[HOWOGE] Selector '{sel}': {len(all_btns)} matches")
for btn in all_btns:
try:
if await btn.is_visible():
apply_btn = btn
logger.info(f"[HOWOGE] Found visible application button: {sel}")
break
except Exception as e:
logger.debug(f"[HOWOGE] Button visibility error: {e}")
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)
result["success"] = True
result["message"] = "Application submitted successfully."
else:
logger.warning("[HOWOGE] No application button found.")
result["message"] = "No application button found."
except Exception as e:
result["message"] = f"Error during application: {e}"
logger.error(f"[HOWOGE] Application error: {e}")
finally:
await page.close()
return result