Download crawler_core.py from cruelface/crawler: direct link, hf CLI and curl.
- Browser
- Download file 39.1 kB
-
https://huggingface.co/spaces/cruelface/crawler/resolve/main/crawler_core.py
- Command line
-
hf download hf://spaces/cruelface/crawler/crawler_core.py
-
curl -L -o crawler_core.py https://huggingface.co/spaces/cruelface/crawler/resolve/main/crawler_core.py
39.1 kB
| import requests | |
| from bs4 import BeautifulSoup, FeatureNotFound | |
| from urllib.parse import urljoin, urlparse, parse_qs, unquote, quote, urlunparse | |
| from collections import deque | |
| import csv | |
| import datetime | |
| import re | |
| import time | |
| from io import StringIO | |
| import json | |
| import hashlib | |
| import html | |
| import logging | |
| import tldextract | |
| from urllib3.util import Retry | |
| from requests.adapters import HTTPAdapter | |
| import threading | |
| class EnhancedWebCrawler: | |
| def __init__(self, start_url, crawl_mode="Standard", keywords=None, status_callback=None, progress_callback=None, result_callback=None): | |
| self.session = self._create_session() | |
| self.start_url = start_url | |
| self.keywords = keywords if keywords else ["gowithguide", "go with guide", "go-with-guide"] | |
| self.main_domain = urlparse(start_url).netloc | |
| self.crawl_mode = crawl_mode | |
| self.max_pages = {"Quick": 5, "Standard": 150, "Complete": 5000}[crawl_mode] | |
| self.visited = set() | |
| self.results = [] | |
| self.queue = deque([start_url]) | |
| self.categories = [] | |
| self.current_category = None | |
| self.status_messages = [] | |
| self.user_stopped = False | |
| self.pages_crawled = 0 | |
| self.redirect_cache = {} | |
| self.internal_links = set() | |
| self.known_shorteners = [ | |
| 'bit.ly', 'tinyurl.com', 'goo.gl', 't.co', 'ow.ly', 'is.gd', | |
| 'buff.ly', 'adf.ly', 'bit.do', 'mcaf.ee', 'su.pr', 'tiny.cc', | |
| 'tidd.ly', 'redirectingat.com', 'go.redirectingat.com', 'go.skimresources.com' | |
| ] | |
| self.awin_domains = ['awin1.com', 'zenaps.com'] | |
| self.potential_affiliate_domains = [ | |
| 'track.', 'go.', 'click.', 'buy.', 'shop.', 'link.', 'visit.', | |
| 'affiliate.', 'partners.', 'tracking.', 'redirect.', 'ref.' | |
| ] | |
| self.potential_affiliate_paths = [ | |
| '/visit', '/go', '/goto', '/redirect', '/click', '/buy', '/shop', | |
| '/link', '/affiliate', '/partner', '/tracking', '/ref', '/out' | |
| ] | |
| self.potential_affiliate_params = [ | |
| 'site', 'url', 'link', 'goto', 'target', 'redirect', 'redirect_to', | |
| 'dest', 'destination', 'u', 'to', 'out', 'away', 'href' | |
| ] | |
| self.crawled_pages_content = {} | |
| self.url_fragments_checked = set() | |
| self.status_callback = status_callback | |
| self.progress_callback = progress_callback | |
| self.result_callback = result_callback | |
| self.setup_logger() | |
| def setup_logger(self): | |
| self.logger = logging.getLogger('crawler') | |
| self.logger.setLevel(logging.INFO) | |
| if not self.logger.handlers: | |
| handler = logging.StreamHandler() | |
| formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') | |
| handler.setFormatter(formatter) | |
| self.logger.addHandler(handler) | |
| def _create_session(self): | |
| session = requests.Session() | |
| retries = Retry( | |
| total=3, | |
| backoff_factor=0.5, | |
| status_forcelist=[429, 500, 502, 503, 504], | |
| allowed_methods=["GET", "HEAD"] | |
| ) | |
| adapter = HTTPAdapter(max_retries=retries) | |
| session.mount("http://", adapter) | |
| session.mount("https://", adapter) | |
| session.headers.update({ | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', | |
| 'Accept-Language': 'en-US,en;q=0.5', | |
| 'Connection': 'keep-alive', | |
| 'Upgrade-Insecure-Requests': '1', | |
| 'Cache-Control': 'max-age=0' | |
| }) | |
| return session | |
| def get_soup(self, html_content): | |
| try: | |
| return BeautifulSoup(html_content, 'lxml') | |
| except FeatureNotFound: | |
| return BeautifulSoup(html_content, 'html.parser') | |
| def is_same_domain(self, url): | |
| main_domain_parts = tldextract.extract(self.start_url) | |
| url_domain_parts = tldextract.extract(url) | |
| return (main_domain_parts.domain == url_domain_parts.domain and | |
| main_domain_parts.suffix == url_domain_parts.suffix) | |
| def is_subdomain_of(self, url_netloc): | |
| main_domain = self.main_domain.replace("www.", "").lower() | |
| url_netloc = url_netloc.replace("www.", "").lower() | |
| return url_netloc.endswith("." + main_domain) or url_netloc == main_domain | |
| def is_relevant_path(self, url): | |
| parsed_url = urlparse(url) | |
| path = parsed_url.path.lower() | |
| if re.search(r'\.(jpg|jpeg|png|gif|svg|pdf|zip|rar|css|js|xml|json)$', path): | |
| return False | |
| if re.search(r'/(login|logout|register|signin|signout|cart|checkout|privacy|terms)/?$', path): | |
| return False | |
| if re.search(r'/(post|article|blog|news|story|travel|guide|destination|affiliate)/', path): | |
| return True | |
| if len(parse_qs(parsed_url.query)) > 3: | |
| return False | |
| return True | |
| def normalize_url(self, url): | |
| parsed = urlparse(url) | |
| normalized = urlunparse((parsed.scheme, parsed.netloc, parsed.path, | |
| parsed.params, parsed.query, '')) | |
| if normalized.endswith('/'): | |
| normalized = normalized[:-1] | |
| return normalized | |
| def looks_like_affiliate_url(self, url): | |
| url_lower = url.lower() | |
| parsed_url = urlparse(url_lower) | |
| netloc = parsed_url.netloc | |
| path = parsed_url.path | |
| if any(shortener in netloc for shortener in self.known_shorteners): | |
| return True | |
| if any(tracker in netloc for tracker in self.potential_affiliate_domains): | |
| return True | |
| if any(domain in netloc for domain in self.awin_domains): | |
| query_params = parse_qs(parsed_url.query) | |
| if 'v' in query_params and query_params['v'][0] == '87121': | |
| return True | |
| if 'awinmid' in query_params and query_params['awinmid'][0] == '87121': | |
| return True | |
| if any(aff_path in path for aff_path in self.potential_affiliate_paths): | |
| return True | |
| query_params = parse_qs(parsed_url.query) | |
| affiliate_params = ['aff', 'affid', 'affiliateid', 'ref', 'refid', 'referral', | |
| 'referralid', 'partner', 'partnerId', 'utm_source'] | |
| for param in affiliate_params: | |
| if param in query_params: | |
| return True | |
| for param in self.potential_affiliate_params: | |
| if param in query_params: | |
| param_value = query_params[param][0].lower() | |
| if any(keyword in param_value for keyword in self.keywords): | |
| return True | |
| tracking_params = ['utm_', 'ref', 'aff', 'source', 'campaign', 'medium'] | |
| tracking_count = sum(1 for param in query_params if any(t in param for t in tracking_params)) | |
| if tracking_count >= 2: | |
| return True | |
| if 'awc' in query_params: | |
| awc_value = query_params['awc'][0] | |
| if '87121' in awc_value: | |
| return True | |
| return False | |
| def extract_redirection_url(self, html_content, url): | |
| soup = self.get_soup(html_content) | |
| redirect_urls = [] | |
| meta_refresh = soup.find('meta', attrs={'http-equiv': re.compile('^refresh$', re.I)}) | |
| if meta_refresh and meta_refresh.get('content'): | |
| match = re.search(r'url=(.+)', meta_refresh['content'], re.I) | |
| if match: | |
| redirect_url = match.group(1).strip() | |
| redirect_urls.append(urljoin(url, redirect_url)) | |
| script_patterns = [ | |
| r'window\.location(?:\.href)?\s*=\s*[\'"](.+?)[\'"]', | |
| r'window\.location\.replace\([\'"](.+?)[\'"]\)', | |
| r'window\.open\([\'"](.+?)[\'"]\)', | |
| r'location\.href\s*=\s*[\'"](.+?)[\'"]', | |
| r'location\.replace\([\'"](.+?)[\'"]\)', | |
| r'setTimeout\([\'"]window\.location\.href=[\'"](.+?)[\'"][\'"]', | |
| r'url:\s*[\'"](.+?)[\'"]', | |
| r'href=[\'"](.+?)[\'"]' | |
| ] | |
| scripts = soup.find_all('script') | |
| for script in scripts: | |
| if script.string: | |
| for pattern in script_patterns: | |
| matches = re.findall(pattern, script.string) | |
| for match in matches: | |
| if len(match) > 10: | |
| redirect_urls.append(urljoin(url, match)) | |
| parsed_url = urlparse(url) | |
| query_params = parse_qs(parsed_url.query) | |
| redirect_params = ['redirect_to', 'redirect', 'url', 'link', 'goto', 'target', 'ued'] | |
| for param in redirect_params: | |
| if param in query_params: | |
| decoded_url = unquote(query_params[param][0]) | |
| redirect_urls.append(urljoin(url, decoded_url)) | |
| return redirect_urls | |
| def check_url_for_keywords(self, url, source_url): | |
| if not url or not isinstance(url, str): | |
| return | |
| url_hash = hashlib.md5(url.encode()).hexdigest() | |
| if url_hash in self.url_fragments_checked: | |
| return | |
| self.url_fragments_checked.add(url_hash) | |
| matched_kws = self.get_matched_keywords(url) | |
| if matched_kws: | |
| self.add_result( | |
| source_url=source_url, | |
| matched_url=url, | |
| element='url', | |
| attribute='href', | |
| content=url, | |
| keywords=matched_kws, | |
| location_type='direct_url' | |
| ) | |
| if self.looks_like_affiliate_url(url): | |
| final_url, history = self.resolve_redirects(url) | |
| if final_url != url: | |
| matched_kws_final = self.get_matched_keywords(final_url) | |
| if matched_kws_final: | |
| self.add_result( | |
| source_url=source_url, | |
| matched_url=final_url, | |
| element='url', | |
| attribute='href', | |
| content=f"Redirected from: {url} to: {final_url}", | |
| keywords=matched_kws_final, | |
| location_type='redirected_url' | |
| ) | |
| for intermediate_url in history: | |
| matched_kws_intermediate = self.get_matched_keywords(intermediate_url) | |
| if matched_kws_intermediate: | |
| self.add_result( | |
| source_url=source_url, | |
| matched_url=intermediate_url, | |
| element='url', | |
| attribute='href', | |
| content=f"Redirect chain URL: {intermediate_url}", | |
| keywords=matched_kws_intermediate, | |
| location_type='redirect_chain_url' | |
| ) | |
| def get_matched_keywords(self, text): | |
| if not text or not isinstance(text, str): | |
| return [] | |
| matched = [] | |
| text_lower = text.lower() | |
| for keyword in self.keywords: | |
| if keyword.lower() in text_lower: | |
| matched.append(keyword) | |
| return matched | |
| def add_result(self, source_url, matched_url, element, attribute, content, keywords, location_type): | |
| result = { | |
| 'source_url': source_url, | |
| 'matched_url': matched_url, | |
| 'keyword': ', '.join(keywords), | |
| 'location_type': location_type, | |
| 'element': element, | |
| 'attribute': attribute, | |
| 'content': content, | |
| 'timestamp': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') | |
| } | |
| self.results.append(result) | |
| if self.result_callback: | |
| self.result_callback(result) | |
| if self.status_callback: | |
| self.status_callback(f"Found match: {matched_url} (Keyword: {result['keyword']})") | |
| def resolve_redirects(self, url): | |
| if url in self.redirect_cache: | |
| return self.redirect_cache[url] | |
| history = [] | |
| final_url = url | |
| try: | |
| response = self.session.head(url, allow_redirects=True, timeout=5) | |
| if response.history: | |
| history = [resp.url for resp in response.history] | |
| final_url = response.url | |
| self.redirect_cache[url] = (final_url, history) | |
| except requests.RequestException: | |
| self.redirect_cache[url] = (url, []) | |
| return self.redirect_cache[url] | |
| def process_url(self, url): | |
| if url in self.visited or self.pages_crawled >= self.max_pages or not url or self.user_stopped: | |
| return [] | |
| self.visited.add(url) | |
| self.pages_crawled += 1 | |
| if self.progress_callback: | |
| self.progress_callback(self.pages_crawled / self.max_pages) | |
| try: | |
| response = self.session.get( | |
| url, | |
| headers={ | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml' | |
| }, | |
| timeout=20, | |
| allow_redirects=True | |
| ) | |
| response.raise_for_status() | |
| content_type = response.headers.get('content-type', '').lower() | |
| if 'text/html' not in content_type: | |
| return [] | |
| html_content = response.text | |
| # self.crawled_pages_content[url] = html_content # REMOVED: Memory leak | |
| soup = self.get_soup(html_content) | |
| matched_kws = self.get_matched_keywords(html_content) | |
| if matched_kws: | |
| self.add_result( | |
| source_url=url, | |
| matched_url=url, | |
| element='page_content', | |
| attribute='text', | |
| content=html_content[:200], | |
| keywords=matched_kws, | |
| location_type='content' | |
| ) | |
| redirect_urls = self.extract_redirection_url(html_content, url) | |
| for redirect_url in redirect_urls: | |
| self.check_url_for_keywords(redirect_url, url) | |
| links = [] | |
| for a_tag in soup.find_all('a', href=True): | |
| href = a_tag.get('href') | |
| if not href: | |
| continue | |
| absolute_url = urljoin(url, href) | |
| absolute_url = self.normalize_url(absolute_url) | |
| if (self.is_same_domain(absolute_url) or self.is_subdomain_of(urlparse(absolute_url).netloc)) and self.is_relevant_path(absolute_url): | |
| links.append(absolute_url) | |
| self.internal_links.add(absolute_url) | |
| self.check_url_for_keywords(absolute_url, url) | |
| return links | |
| except requests.RequestException as e: | |
| status_code = e.response.status_code if (e.response is not None) else None | |
| error_message = self.get_user_friendly_error(status_code, url) | |
| self.logger.warning(error_message) | |
| if self.status_callback: | |
| self.status_callback(error_message) | |
| return [] | |
| def get_user_friendly_error(self, status_code, url): | |
| error_messages = { | |
| 400: "Bad Request", | |
| 401: "Unauthorized", | |
| 403: "Forbidden", | |
| 404: "URL not found", | |
| 500: "Internal Server Error", | |
| 502: "Bad Gateway", | |
| 503: "Service Unavailable", | |
| 504: "Gateway Timeout", | |
| } | |
| if status_code is None: | |
| message = "Connection error" | |
| else: | |
| message = error_messages.get(status_code, f"HTTP {status_code}") | |
| return f"{message} for URL: {url}" | |
| def start_crawling(self): | |
| self.reset_state() | |
| if self.status_callback: | |
| self.status_callback(f"Starting crawl of {self.start_url} in {self.crawl_mode} mode") | |
| while self.queue and not self.user_stopped and self.pages_crawled < self.max_pages: | |
| url = self.queue.popleft() | |
| new_urls = self.process_url(url) | |
| for new_url in new_urls: | |
| if (new_url not in self.visited and new_url not in self.queue and | |
| self.pages_crawled < self.max_pages): | |
| self.queue.append(new_url) | |
| if self.progress_callback: | |
| self.progress_callback(min(self.pages_crawled / self.max_pages, 1.0)) | |
| if self.results: | |
| if self.status_callback: | |
| self.status_callback(f"Found {len(self.results)} matches") | |
| if self.status_callback: | |
| self.status_callback("Crawling completed") | |
| return self.results | |
| def reset_state(self): | |
| self.visited = set() | |
| self.queue = deque([self.start_url]) | |
| self.results = [] | |
| self.pages_crawled = 0 | |
| self.redirect_cache = {} | |
| self.internal_links = set() | |
| # self.crawled_pages_content = {} # REMOVED: Memory leak | |
| self.url_fragments_checked = set() | |
| def _ddg_search_via_library(query, max_results=30): | |
| results = [] | |
| ddgs_module = None | |
| for pkg in ('ddgs', 'duckduckgo_search'): | |
| try: | |
| mod = __import__(pkg, fromlist=['DDGS']) | |
| ddgs_module = getattr(mod, 'DDGS') | |
| break | |
| except (ImportError, AttributeError): | |
| continue | |
| if ddgs_module is None: | |
| raise ImportError("Neither 'ddgs' nor 'duckduckgo_search' library is installed.") | |
| with ddgs_module() as ddgs: | |
| for r in ddgs.text(query, max_results=max_results): | |
| results.append({ | |
| 'title': r.get('title', ''), | |
| 'url': r.get('href', r.get('url', '')), | |
| 'snippet': r.get('body', r.get('snippet', '')) | |
| }) | |
| return results | |
| def _ddg_search_via_html(query, max_results=30): | |
| results = [] | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept-Language': 'en-US,en;q=0.9', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
| 'Referer': 'https://html.duckduckgo.com/', | |
| }) | |
| ddg_url = 'https://html.duckduckgo.com/html/' | |
| params = {'q': query, 'kl': 'us-en'} | |
| try: | |
| response = session.get(ddg_url, params=params, timeout=15) | |
| response.raise_for_status() | |
| except requests.RequestException as exc: | |
| raise RuntimeError(f"DuckDuckGo HTML request failed: {exc}") | |
| try: | |
| soup = BeautifulSoup(response.text, 'lxml') | |
| except FeatureNotFound: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| items = soup.select('#links .result') | |
| for item in items: | |
| if len(results) >= max_results: | |
| break | |
| title_tag = item.select_one('.result__a') | |
| if not title_tag: | |
| continue | |
| title = title_tag.get_text(strip=True) | |
| raw_href = title_tag.get('href', '') | |
| if raw_href.startswith('//'): | |
| raw_href = 'https:' + raw_href | |
| parsed_href = urlparse(raw_href) | |
| qs = parse_qs(parsed_href.query) | |
| if 'uddg' in qs: | |
| real_url = unquote(qs['uddg'][0]) | |
| else: | |
| real_url = raw_href | |
| snippet_tag = item.select_one('.result__snippet') | |
| snippet = snippet_tag.get_text(strip=True) if snippet_tag else '' | |
| if real_url and real_url.startswith('http'): | |
| results.append({'title': title, 'url': real_url, 'snippet': snippet}) | |
| return results | |
| def _post_filter_results(results, domain, keywords): | |
| if not domain or not keywords: | |
| return results | |
| bare_domain = domain.lower() | |
| if bare_domain.startswith('www.'): | |
| bare_domain = bare_domain[4:] | |
| kw_lower = [kw.lower() for kw in keywords] | |
| filtered = [] | |
| for r in results: | |
| url = r.get('url', '') | |
| title = r.get('title', '') | |
| snippet = r.get('snippet', '') | |
| try: | |
| result_netloc = urlparse(url).netloc.lower() | |
| if result_netloc.startswith('www.'): | |
| result_netloc = result_netloc[4:] | |
| except Exception: | |
| continue | |
| if result_netloc != bare_domain and not result_netloc.endswith('.' + bare_domain): | |
| continue | |
| haystack = (url + ' ' + title + ' ' + snippet).lower() | |
| if not any(kw in haystack for kw in kw_lower): | |
| continue | |
| filtered.append(r) | |
| return filtered | |
| def _swisscows_search_via_api(query, max_results=30): | |
| import base64 | |
| results = [] | |
| def rot13_swap(s): | |
| alphabet = 'abcdefghijklmnopqrstuvwxyz' | |
| res = [] | |
| for c in s: | |
| if c.lower() in alphabet: | |
| idx = alphabet.index(c.lower()) | |
| new_idx = (idx + 13) % 26 | |
| shifted = alphabet[new_idx] | |
| if c.isupper(): | |
| res.append(shifted.lower()) | |
| else: | |
| res.append(shifted.upper()) | |
| else: | |
| res.append(c) | |
| return ''.join(res) | |
| def generate_nonce(length=32): | |
| import random | |
| chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~' | |
| return ''.join(random.choice(chars) for _ in range(length)) | |
| def compute_headers(endpoint, query_params): | |
| nonce = generate_nonce(32) | |
| rot_nonce = rot13_swap(nonce) | |
| sorted_keys = sorted(query_params.keys()) | |
| query_parts = [] | |
| for k in sorted_keys: | |
| query_parts.append(f'{k}={query_params[k]}') | |
| query_string = '?' + '&'.join(query_parts) | |
| input_string = endpoint + query_string + rot_nonce | |
| hash_bytes = hashlib.sha256(input_string.encode('utf-8')).digest() | |
| base64_str = base64.b64encode(hash_bytes).decode('utf-8') | |
| signature = base64_str.replace('=', '').replace('+', '-').replace('/', '_') | |
| return { | |
| 'X-Request-Nonce': nonce, | |
| 'X-Request-Signature': signature | |
| } | |
| endpoint = '/v5/web/search' | |
| query_params = { | |
| 'query': query, | |
| 'offset': '0', | |
| 'itemsCount': str(min(max_results, 10)), | |
| 'locale': 'en-US', | |
| 'freshness': 'All', | |
| 'spellcheck': 'true' | |
| } | |
| try: | |
| headers = compute_headers(endpoint, query_params) | |
| headers['User-Agent'] = ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ) | |
| headers['Accept'] = 'application/json, text/plain, */*' | |
| session = requests.Session() | |
| r = session.get('https://api.swisscows.com' + endpoint, params=query_params, headers=headers, timeout=15) | |
| r.raise_for_status() | |
| payload = r.json().get('payload', '') | |
| if not payload or '.' not in payload: | |
| return [] | |
| parts = payload.split('.') | |
| if len(parts) < 2: | |
| return [] | |
| padded = parts[1] + '=' * (4 - len(parts[1]) % 4) | |
| decoded = base64.b64decode(padded.replace('-', '+').replace('_', '/')).decode('utf-8') | |
| data = json.loads(decoded) | |
| for item in data.get('items', []): | |
| title = item.get('name', '') | |
| url = item.get('url', '') | |
| snippet = item.get('description', '') | |
| if snippet: | |
| snippet = re.sub(r'<[^>]+>', '', snippet) | |
| snippet = html.unescape(snippet) | |
| if url and url.startswith('http'): | |
| results.append({ | |
| 'title': title, | |
| 'url': url, | |
| 'snippet': snippet | |
| }) | |
| except Exception as exc: | |
| raise RuntimeError(f"Swisscows request failed: {exc}") | |
| return results | |
| def _yahoo_search_via_html(query, max_results=30): | |
| results = [] | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| }) | |
| url = 'https://search.yahoo.com/search' | |
| params = {'p': query} | |
| try: | |
| response = session.get(url, params=params, timeout=15) | |
| response.raise_for_status() | |
| except requests.RequestException as exc: | |
| raise RuntimeError(f"Yahoo HTML request failed: {exc}") | |
| try: | |
| soup = BeautifulSoup(response.text, 'lxml') | |
| except FeatureNotFound: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| items = soup.select('.algo') | |
| for item in items: | |
| if len(results) >= max_results: | |
| break | |
| title_tag = item.select_one('.compTitle h3') or item.select_one('.compTitle .title') | |
| a_tag = item.select_one('.compTitle a') or item.select_one('a') | |
| snippet_tag = item.select_one('.compText') | |
| if not title_tag or not a_tag: | |
| continue | |
| title = title_tag.get_text(strip=True) | |
| raw_href = a_tag.get('href', '') | |
| real_url = raw_href | |
| if '/RU=' in raw_href: | |
| m = re.search(r'/RU=([^/]+)', raw_href) | |
| if m: | |
| real_url = unquote(m.group(1)) | |
| snippet = snippet_tag.get_text(strip=True) if snippet_tag else '' | |
| if real_url and real_url.startswith('http'): | |
| results.append({'title': title, 'url': real_url, 'snippet': snippet}) | |
| return results | |
| def _bing_search_via_html(query, max_results=30): | |
| """Fallback: scrape Bing HTML search results.""" | |
| results = [] | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept-Language': 'en-US,en;q=0.9', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
| }) | |
| url = 'https://www.bing.com/search' | |
| params = {'q': query, 'count': str(min(max_results, 50))} | |
| try: | |
| response = session.get(url, params=params, timeout=15) | |
| response.raise_for_status() | |
| except requests.RequestException as exc: | |
| raise RuntimeError(f"Bing HTML request failed: {exc}") | |
| try: | |
| soup = BeautifulSoup(response.text, 'lxml') | |
| except FeatureNotFound: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # Bing organic results live in <li class="b_algo"> | |
| items = soup.select('li.b_algo') | |
| for item in items: | |
| if len(results) >= max_results: | |
| break | |
| a_tag = item.select_one('h2 a') | |
| if not a_tag: | |
| continue | |
| title = a_tag.get_text(strip=True) | |
| raw_href = a_tag.get('href', '') | |
| snippet_tag = item.select_one('.b_caption p') or item.select_one('p') | |
| snippet = snippet_tag.get_text(strip=True) if snippet_tag else '' | |
| if raw_href and raw_href.startswith('http'): | |
| results.append({'title': title, 'url': raw_href, 'snippet': snippet}) | |
| return results | |
| def _brave_search_via_html(query, max_results=30): | |
| """Fallback: scrape Brave Search HTML results. Brave is less aggressive on cloud IPs.""" | |
| results = [] | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept-Language': 'en-US,en;q=0.9', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
| }) | |
| url = 'https://search.brave.com/search' | |
| params = {'q': query, 'num': str(min(max_results, 50))} | |
| try: | |
| response = session.get(url, params=params, timeout=15) | |
| response.raise_for_status() | |
| except requests.RequestException as exc: | |
| raise RuntimeError(f"Brave HTML request failed: {exc}") | |
| try: | |
| soup = BeautifulSoup(response.text, 'lxml') | |
| except FeatureNotFound: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # Brave organic results are in <div class="result"> blocks | |
| for div in soup.select('div.result'): | |
| if len(results) >= max_results: | |
| break | |
| a_tag = div.select_one('a[data-url]') or div.select_one('a') | |
| if not a_tag: | |
| continue | |
| raw_href = a_tag.get('href', '') | |
| if not raw_href.startswith('http'): | |
| continue | |
| title_tag = div.select_one('h2') or div.select_one('h3') | |
| title = title_tag.get_text(strip=True) if title_tag else '' | |
| snippet_tag = div.select_one('p') | |
| snippet = snippet_tag.get_text(strip=True) if snippet_tag else '' | |
| results.append({'title': title, 'url': raw_href, 'snippet': snippet}) | |
| return results | |
| def _google_search_via_html(query, max_results=30): | |
| """Fallback: scrape Google HTML search results (same as before).""" | |
| results = [] | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept-Language': 'en-US,en;q=0.9', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
| }) | |
| url = 'https://www.google.com/search' | |
| params = {'q': query, 'num': str(min(max_results, 100)), 'hl': 'en'} | |
| try: | |
| response = session.get(url, params=params, timeout=15) | |
| response.raise_for_status() | |
| except requests.RequestException as exc: | |
| raise RuntimeError(f"Google HTML request failed: {exc}") | |
| try: | |
| soup = BeautifulSoup(response.text, 'lxml') | |
| except FeatureNotFound: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| # Google organic results: try multiple known selectors | |
| for div in soup.select('div.g, div.tF2Cxc, div.yuRUbf'): | |
| if len(results) >= max_results: | |
| break | |
| a_tag = div.select_one('a[href]') | |
| if not a_tag: | |
| continue | |
| raw_href = a_tag.get('href', '') | |
| if not raw_href.startswith('http'): | |
| continue | |
| # Skip google internal links | |
| if 'google.com' in raw_href and '/search' in raw_href: | |
| continue | |
| title_tag = div.select_one('h3') | |
| title = title_tag.get_text(strip=True) if title_tag else '' | |
| snippet_tag = div.select_one('div.VwiC3b, span.aCOpRe, div.IsZvec') | |
| snippet = snippet_tag.get_text(strip=True) if snippet_tag else '' | |
| results.append({'title': title, 'url': raw_href, 'snippet': snippet}) | |
| return results | |
| def _searxng_search_via_html(query, max_results=30): | |
| """Fallback: query a list of public SearXNG instances and aggregate results. | |
| If an instance fails, it is skipped and the next one is tried. | |
| """ | |
| instances = [ | |
| 'https://searx.be', | |
| 'https://searxng.eu', | |
| 'https://searx.fmac.xyz', | |
| 'https://searx.tiekoetter.com', | |
| 'https://searx.gnous.eu', | |
| ] | |
| results = [] | |
| for base in instances: | |
| try: | |
| url = f"{base}/search" | |
| params = {'q': query, 'format': 'json', 'num': str(min(max_results, 30))} | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept': 'application/json', | |
| }) | |
| resp = session.get(url, params=params, timeout=12) | |
| resp.raise_for_status() | |
| data = resp.json() | |
| for item in data.get('results', []): | |
| if len(results) >= max_results: | |
| break | |
| title = item.get('title', '') | |
| link = item.get('url', '') | |
| snippet = item.get('content', '') or item.get('snippet', '') | |
| if link and link.startswith('http'): | |
| results.append({'title': title, 'url': link, 'snippet': snippet}) | |
| if results: | |
| break # stop after first successful instance | |
| except Exception: | |
| continue # try next instance silently | |
| return results | |
| """Fallback: query a list of public SearXNG instances and aggregate results. | |
| If an instance fails, it is skipped and the next one is tried. | |
| """ | |
| instances = [ | |
| 'https://searx.be', | |
| 'https://searxng.eu', | |
| 'https://searx.fmac.xyz', | |
| 'https://searx.tiekoetter.com', | |
| 'https://searx.gnous.eu', | |
| ] | |
| results = [] | |
| for base in instances: | |
| try: | |
| url = f"{base}/search" | |
| params = {'q': query, 'format': 'json', 'num': str(min(max_results, 30))} | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept': 'application/json', | |
| }) | |
| resp = session.get(url, params=params, timeout=12) | |
| resp.raise_for_status() | |
| data = resp.json() | |
| for item in data.get('results', []): | |
| if len(results) >= max_results: | |
| break | |
| title = item.get('title', '') | |
| link = item.get('url', '') | |
| snippet = item.get('content', '') or item.get('snippet', '') | |
| if link and link.startswith('http'): | |
| results.append({'title': title, 'url': link, 'snippet': snippet}) | |
| if results: | |
| break # stop after first successful instance | |
| except Exception: | |
| continue # try next instance silently | |
| return results | |
| def _startpage_search_via_html(query, max_results=30): | |
| """Fallback: search via Startpage (privacy proxy to Google).""" | |
| results = [] | |
| session = requests.Session() | |
| session.headers.update({ | |
| 'User-Agent': ( | |
| 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' | |
| 'AppleWebKit/537.36 (KHTML, like Gecko) ' | |
| 'Chrome/124.0.0.0 Safari/537.36' | |
| ), | |
| 'Accept-Language': 'en-US,en;q=0.9', | |
| 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', | |
| }) | |
| url = 'https://www.startpage.com/do/search' | |
| params = {'query': query, 'cat': 'web', 'language': 'english'} | |
| try: | |
| response = session.get(url, params=params, timeout=15) | |
| response.raise_for_status() | |
| except requests.RequestException as exc: | |
| raise RuntimeError(f"Startpage HTML request failed: {exc}") | |
| try: | |
| soup = BeautifulSoup(response.text, 'lxml') | |
| except FeatureNotFound: | |
| soup = BeautifulSoup(response.text, 'html.parser') | |
| for div in soup.select('div.w-gl__result'): # generic selector used by Startpage | |
| if len(results) >= max_results: | |
| break | |
| a_tag = div.select_one('a') | |
| if not a_tag: | |
| continue | |
| raw_href = a_tag.get('href', '') | |
| if not raw_href.startswith('http'): | |
| continue | |
| title_tag = div.select_one('h3') | |
| title = title_tag.get_text(strip=True) if title_tag else '' | |
| snippet_tag = div.select_one('p') | |
| snippet = snippet_tag.get_text(strip=True) if snippet_tag else '' | |
| results.append({'title': title, 'url': raw_href, 'snippet': snippet}) | |
| return results | |
| def ddg_find_urls(query, domain='', keywords=None, max_results=20): | |
| if keywords is None: | |
| keywords = [] | |
| fetch_count = max(max_results * 4, 60) | |
| raw_results = [] | |
| method = 'none' | |
| ddg_error = '' | |
| swiss_error = '' | |
| yahoo_error = '' | |
| try: | |
| raw_results = _ddg_search_via_library(query, max_results=fetch_count) | |
| method = 'library' | |
| except Exception as e: | |
| ddg_error = f"Library: {e}" | |
| if not raw_results: | |
| try: | |
| raw_results = _ddg_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'html_scrape' | |
| except Exception as html_err: | |
| ddg_error += f" | HTML: {html_err}" | |
| if not raw_results: | |
| try: | |
| raw_results = _swisscows_search_via_api(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'swisscows_api' | |
| except Exception as swiss_err: | |
| swiss_error = str(swiss_err) | |
| if not raw_results: | |
| try: | |
| raw_results = _yahoo_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'yahoo_scrape' | |
| except Exception as yahoo_err: | |
| yahoo_error = str(yahoo_err) | |
| bing_error = '' | |
| google_error = '' | |
| brave_error = '' | |
| searx_error = '' | |
| startpage_error = '' | |
| if not raw_results: | |
| try: | |
| raw_results = _bing_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'bing_scrape' | |
| except Exception as bing_err: | |
| bing_error = str(bing_err) | |
| if not raw_results: | |
| try: | |
| raw_results = _google_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'google_scrape' | |
| except Exception as google_err: | |
| google_error = str(google_err) | |
| if not raw_results: | |
| try: | |
| raw_results = _brave_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'brave_scrape' | |
| except Exception as brave_err: | |
| brave_error = str(brave_err) | |
| if not raw_results: | |
| try: | |
| raw_results = _searxng_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'searxng_api' | |
| except Exception as searx_err: | |
| searx_error = str(searx_err) | |
| if not raw_results: | |
| try: | |
| raw_results = _startpage_search_via_html(query, max_results=fetch_count) | |
| if raw_results: | |
| method = 'startpage_scrape' | |
| except Exception as startpage_err: | |
| startpage_error = str(startpage_err) | |
| if not raw_results: | |
| combined_error = f"DDG failed ({ddg_error}). Swisscows failed ({swiss_error}). Yahoo failed ({yahoo_error}). Bing failed ({bing_error}). Google failed ({google_error}). Brave failed ({brave_error}). SearXNG failed ({searx_error}). Startpage failed ({startpage_error})." | |
| return [], 'none', combined_error | |
| filtered = _post_filter_results(raw_results, domain, keywords) | |
| if raw_results and not filtered: | |
| return raw_results, method, 'NO_KEYWORD_DOMAIN_MATCH' | |
| return filtered, method, '' | |