webook / utils.py
Mohammed Foud
Add application file
f959aff
import logging
from playwright.sync_api import sync_playwright
import os
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('logs/webook_actions.log'),
logging.StreamHandler()
]
)
logger = logging.getLogger(__name__)
class WeBookBase:
def __init__(self, profile_dir=None, page=None):
self.profile_dir = profile_dir or os.path.join(Path.home(), '.webook_profile')
self.playwright = None
self.browser = None
self.page = page # Accept existing page
self.context = None # Keep track of context if created here
def _handle_cookies(self):
try:
cookie_banner = self.page.locator('#cookie_consent')
if cookie_banner.is_visible():
accept_button = self.page.get_by_role('button', name='Accept all')
if accept_button.is_visible():
accept_button.click()
logger.info("Cookie consent accepted")
except Exception as e:
logger.warning(f"Cookie handling issue: {str(e)}")
def _setup_browser(self):
if not self.page: # Only set up if page is not provided
self.playwright = sync_playwright().start()
self.context = self.playwright.chromium.launch_persistent_context(
user_data_dir=self.profile_dir,
headless=False,
args=[]
)
self.page = self.context.pages[0] if self.context.pages else self.context.new_page()
logger.info(f"Using profile directory: {self.profile_dir}")
# Return the page and context for external management
return self.context, self.page
# Removed the cleanup method
# def cleanup(self):
# if hasattr(self, 'page') and self.page:
# self.page.close()
# if hasattr(self, 'browser') and self.browser:
# self.browser.close()
# if hasattr(self, 'playwright') and self.playwright:
# self.playwright.stop()