Spaces:
Sleeping
Sleeping
File size: 1,858 Bytes
a65c815 34acb60 a65c815 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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 |