import httpx import random from bs4 import BeautifulSoup from config import USER_AGENTS async def extract_page_data(url: str, product_name: str, client: httpx.AsyncClient = None) -> tuple: """Fetches web targets dynamically swapping modern user-agent strings line-by-line to extract pricing indicators""" try: headers = {"User-Agent": random.choice(USER_AGENTS)} html_content = "" if client is not None: res = await client.get(url, headers=headers, timeout=6.0) html_content = res.text else: async with httpx.AsyncClient(trust_env=False) as standalone_client: res = await standalone_client.get(url, headers=headers, timeout=6.0) html_content = res.text soup = BeautifulSoup(html_content, 'html.parser') img_url = None og_img = soup.find("meta", property="og:image") or soup.find("meta", attrs={"name": "og:image"}) if og_img: img_url = og_img.get("content") for s in soup(["script", "style", "nav", "footer", "header", "aside"]): s.extract() raw_lines = soup.get_text(separator='\n').split('\n') keywords = [k.lower() for k in product_name.split() if len(k) > 2] filtered_chunks = [] for line in raw_lines: line_clean = line.strip() if not line_clean: continue if any(c in line_clean for c in ['$', 'USD', 'Price']) or any(k in line_clean.lower() for k in keywords): if len(line_clean) < 300: filtered_chunks.append(line_clean) dense_text = " | ".join(filtered_chunks)[:1500] return dense_text, img_url except Exception as e: print(f"❌ [Network Scraper Exception] Failed fetching {url}: {e}") return None, None