Feature: custom extraction (CSS/XPath) and list mode

Custom extraction: rules set under Settings > Extraction pull values
out of every crawled page with a CSS selector or an XPath expression
(text, inner HTML, outer HTML or an attribute). Results show in a new
Custom Extraction tab, in the URL details, and in exports as one
extract_<name> column per rule. They persist in SQLite. Invalid
selectors are refused on save, naming the rule. Adds lxml for XPath.

List mode: a Spider | List toggle above the URL box. List mode checks
exactly the pasted or uploaded URLs, on any number of sites, records
links without following them, skips sitemap discovery and outbound
link probing, and reports robots.txt-disallowed URLs as blocked rows.
Resume keeps the whole remaining list.

Also: robots.txt is fetched once per host instead of once per worker,
and a failed start now shows its reason instead of "undefined".

Adds test_list_mode_fetches_only_the_list and test_custom_extraction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
PhialityandClaude Opus 5.5 committed 2026-11-04 04:22:09 +11:00
1 parent 5ae2792614
commit 8f4d31d560
12 files changed
+1159 -56

No files matched your search

+62 -2
View File
@@ -9,6 +9,7 @@ import argparse
import secrets
import string
import os
import re
import base64
from io import StringIO, BytesIO
from datetime import datetime, timedelta
@@ -327,6 +328,46 @@ def start_cleanup_thread():
cleanup_thread.start()
print("Started crawler instance cleanup thread")
def flatten_custom_extraction(urls, fields, join=True):
"""Expand the custom_extraction export field into one column per
extractor, named extract_<name>, in the order the rules ran.
Returns (rows, fields). Rows are shallow per-row dicts holding only
the exported fields. Multiple matches are joined with " | " unless
``join`` is False (JSON keeps them as a list).
"""
if 'custom_extraction' not in fields:
return urls, fields
names = []
for url_data in urls:
for name in (url_data.get('custom_extraction') or {}):
if name not in names:
names.append(name)
columns = {}
for name in names:
slug = re.sub(r'[^0-9A-Za-z]+', '_', name).strip('_').lower() or 'field'
key, n = f'extract_{slug}', 2
while key in columns.values() or key in fields:
key, n = f'extract_{slug}_{n}', n + 1
columns[name] = key
at = fields.index('custom_extraction')
plain = [f for f in fields if f != 'custom_extraction']
new_fields = fields[:at] + list(columns.values()) + fields[at + 1:]
def row(url_data):
out = {f: url_data.get(f, '') for f in plain}
extracted = url_data.get('custom_extraction') or {}
for name, key in columns.items():
values = extracted.get(name) or []
out[key] = ' | '.join(values) if join else values
return out
return [row(u) for u in urls], new_fields
def generate_csv_export(urls, fields):
"""Generate CSV export content"""
output = StringIO()
@@ -782,6 +823,14 @@ def start_crawl():
data = request.get_json()
url = data.get('url')
# List mode: crawl exactly these URLs, follow no links
url_list = None
if data.get('mode') == 'list':
url_list = data.get('urls')
if not isinstance(url_list, list) or len(url_list) == 0:
return jsonify({'success': False, 'error': 'List mode needs at least one URL'})
url = url or str(url_list[0])
if not url:
return jsonify({'success': False, 'error': 'URL is required'})
@@ -822,7 +871,8 @@ def start_crawl():
crawler.config['demo_memory_limit_bytes'] = int(1.5 * 1024 * 1024 * 1024) # 1.5GB
# Pass user_id and session_id for database persistence
success, message = crawler.start_crawl(url, user_id=user_id, session_id=session_id)
success, message = crawler.start_crawl(url, user_id=user_id, session_id=session_id,
url_list=url_list)
# Store crawl_id in session
if success and crawler.crawl_id:
@@ -830,7 +880,12 @@ def start_crawl():
# Also log to old crawl_history for compatibility
log_crawl_start(user_id, url)
return jsonify({'success': success, 'message': message, 'crawl_id': crawler.crawl_id})
response = {'success': success, 'message': message, 'crawl_id': crawler.crawl_id}
if not success:
response['error'] = message
elif url_list is not None:
response['list_count'] = crawler.stats['discovered']
return jsonify(response)
@app.route('/api/stop_crawl', methods=['POST'])
@login_required
@@ -1430,6 +1485,9 @@ def export_stream():
if not regular_fields:
return jsonify({'success': False, 'error': 'No fields selected'}), 400
urls, regular_fields = flatten_custom_extraction(
urls, regular_fields, join=export_format != 'json')
if export_format == 'json':
return Response(
_stream_urls_json(urls, regular_fields),
@@ -1828,6 +1886,8 @@ def export_data():
# Generate regular export if there are regular fields
if regular_fields:
urls, regular_fields = flatten_custom_extraction(
urls, regular_fields, join=export_format != 'json')
if export_format == 'csv':
regular_content = generate_csv_export(urls, regular_fields)
regular_mimetype = 'text/csv'
+1
View File
@@ -1,5 +1,6 @@
requests==2.31.0
beautifulsoup4==4.12.2
lxml
urllib3==2.0.7
flask==2.3.3
flask-compress
+178
View File
@@ -0,0 +1,178 @@
"""Custom extraction: pull user-defined values out of each page.
Each rule names a column and selects nodes with a CSS selector or an
XPath expression, then reads one of: the visible text, the inner HTML,
the outer HTML, or an attribute. Results land on the page result as
``custom_extraction = {rule name: [values]}``.
"""
import re
import soupsieve
from lxml import etree, html as lxml_html
SELECTOR_TYPES = ('css', 'xpath')
EXTRACT_MODES = ('text', 'inner_html', 'outer_html', 'attribute')
MAX_RULES = 30
MAX_MATCHES_PER_RULE = 50
MAX_VALUE_CHARS = 2000
_WHITESPACE = re.compile(r'\s+')
def _clean_text(text):
return _WHITESPACE.sub(' ', text or '').strip()
def normalize_rules(raw_rules):
"""Validate rules and return (rules, errors).
Rules missing a name or selector are dropped silently: those are
blank rows left in the settings editor. Rules with a selector that
fails to compile are reported in ``errors``.
"""
rules, errors, seen = [], [], set()
if not isinstance(raw_rules, list):
return [], ['Custom extraction rules must be a list']
for raw in raw_rules:
if not isinstance(raw, dict):
continue
name = str(raw.get('name') or '').strip()
selector = str(raw.get('selector') or '').strip()
if not (name and selector):
continue
sel_type = str(raw.get('type') or 'css').lower()
mode = str(raw.get('mode') or 'text').lower()
attribute = str(raw.get('attribute') or '').strip()
if name in seen:
errors.append(f'"{name}": duplicate extractor name')
continue
if sel_type not in SELECTOR_TYPES:
errors.append(f'"{name}": unknown selector type {sel_type}')
continue
if mode not in EXTRACT_MODES:
errors.append(f'"{name}": unknown extract mode {mode}')
continue
if mode == 'attribute' and not attribute:
errors.append(f'"{name}": attribute mode needs an attribute name')
continue
try:
if sel_type == 'css':
compiled = soupsieve.compile(selector)
else:
compiled = etree.XPath(selector)
except Exception as exc:
reason = (str(exc).splitlines() or ['syntax error'])[0]
label = 'XPath' if sel_type == 'xpath' else 'CSS selector'
errors.append(f'"{name}": invalid {label} ({reason})')
continue
seen.add(name)
rules.append({
'name': name, 'type': sel_type, 'selector': selector,
'mode': mode, 'attribute': attribute, '_compiled': compiled,
})
if len(rules) > MAX_RULES:
errors.append(f'At most {MAX_RULES} extractors are allowed')
rules = rules[:MAX_RULES]
return rules, errors
class CustomExtractor:
"""Applies a fixed set of extraction rules to page HTML."""
def __init__(self, raw_rules):
self.rules, self.errors = normalize_rules(raw_rules)
self._needs_lxml = any(r['type'] == 'xpath' for r in self.rules)
def __bool__(self):
return bool(self.rules)
def extract(self, soup, raw_html):
"""Return {rule name: [values]} for one page.
``soup`` is the BeautifulSoup tree the crawler already built.
``raw_html`` (str or bytes) feeds lxml for XPath rules.
"""
tree = self._lxml_tree(raw_html) if self._needs_lxml else None
out = {}
for rule in self.rules:
try:
if rule['type'] == 'css':
values = self._css(rule, soup)
elif tree is not None:
values = self._xpath(rule, tree)
else:
values = []
except Exception as exc:
values = [f'[extraction error: {exc}]']
out[rule['name']] = [v[:MAX_VALUE_CHARS] for v in values]
return out
@staticmethod
def _lxml_tree(raw_html):
if not raw_html:
return None
if isinstance(raw_html, str):
raw_html = raw_html.encode('utf-8')
try:
return lxml_html.document_fromstring(raw_html)
except (etree.ParserError, ValueError):
return None
@staticmethod
def _css(rule, soup):
values = []
for el in rule['_compiled'].select(soup, limit=MAX_MATCHES_PER_RULE):
mode = rule['mode']
if mode == 'text':
value = _clean_text(el.get_text(' '))
elif mode == 'inner_html':
value = el.decode_contents().strip()
elif mode == 'outer_html':
value = str(el).strip()
else:
value = el.get(rule['attribute'])
if isinstance(value, list):
value = ' '.join(value)
if value:
values.append(value)
return values
@staticmethod
def _xpath(rule, tree):
result = rule['_compiled'](tree)
# count(), boolean() and string() return scalars
if isinstance(result, bool):
return ['true' if result else 'false']
if isinstance(result, float):
return [str(int(result)) if result.is_integer() else str(result)]
if isinstance(result, str):
text = _clean_text(result)
return [text] if text else []
values = []
for node in result[:MAX_MATCHES_PER_RULE]:
if isinstance(node, str):
value = _clean_text(node)
elif not isinstance(node.tag, str):
continue # comments and processing instructions
elif rule['mode'] == 'text':
value = _clean_text(node.text_content())
elif rule['mode'] == 'inner_html':
value = ((node.text or '') + ''.join(
etree.tostring(child, encoding='unicode', method='html')
for child in node)).strip()
elif rule['mode'] == 'outer_html':
value = etree.tostring(node, encoding='unicode', method='html',
with_tail=False).strip()
else:
value = node.get(rule['attribute'])
if value:
values.append(value)
return values
+19 -3
View File
@@ -136,6 +136,12 @@ def init_crawl_tables():
except sqlite3.OperationalError:
pass # Column already exists
# Migration: custom_extraction, JSON {rule name: [values]}
try:
cursor.execute('ALTER TABLE crawled_urls ADD COLUMN custom_extraction TEXT')
except sqlite3.OperationalError:
pass # Column already exists
# Links table
cursor.execute('''
CREATE TABLE IF NOT EXISTS crawl_links (
@@ -314,7 +320,9 @@ def save_url_batch(crawl_id, urls):
url_data.get('javascript_rendered', False),
url_data.get('error_type'),
url_data.get('render_time'),
url_data.get('link_check_only', False)
url_data.get('link_check_only', False),
(json.dumps(url_data['custom_extraction'])
if url_data.get('custom_extraction') is not None else None)
)
rows.append(row)
@@ -326,8 +334,8 @@ def save_url_batch(crawl_id, urls):
meta_tags, og_tags, twitter_tags, json_ld, analytics, images,
hreflang, schema_org, redirects, linked_from,
external_links, internal_links, response_time, javascript_rendered,
error_type, render_time, link_check_only
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
error_type, render_time, link_check_only, custom_extraction
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
''', rows)
print(f"Saved {len(urls)} URLs to database for crawl {crawl_id}")
@@ -538,6 +546,14 @@ def load_crawled_urls(crawl_id, limit=None, offset=0):
except:
url_data[field] = []
# Rows saved without extraction rules keep no key
extraction = url_data.pop('custom_extraction', None)
if extraction:
try:
url_data['custom_extraction'] = json.loads(extraction)
except ValueError:
pass
urls.append(url_data)
return urls
+127 -33
View File
@@ -79,6 +79,10 @@ from src.core.issue_detector import IssueDetector
from src.core.memory_monitor import MemoryMonitor
from src.core.memory_profiler import UserMemoryTracker
from src.core.event_log import CrawlEventLog
from src.core.custom_extractor import CustomExtractor
# Upper bound on URLs accepted for one list-mode crawl
MAX_LIST_URLS = 100000
class WebCrawler:
@@ -105,6 +109,7 @@ class WebCrawler:
self.js_renderer = None
self.sitemap_parser = None
self.issue_detector = None
self.custom_extractor = None
self.seo_extractor = SEOExtractor()
self.memory_monitor = MemoryMonitor()
self.user_memory = UserMemoryTracker()
@@ -149,8 +154,11 @@ class WebCrawler:
# Thread reference
self.crawl_thread = None
# Robots.txt cache
# Robots.txt cache, with one lock per robots URL so parallel
# workers on the same host fetch it once
self._robots_cache = {}
self._robots_locks = {}
self._robots_locks_guard = threading.Lock()
# HEAD status cache (avoids re-checking the same URL across pages)
self._head_status_cache = {}
@@ -225,6 +233,8 @@ class WebCrawler:
'js_viewport_width': 1920,
'js_viewport_height': 1080,
'js_max_concurrent_pages': 3,
'custom_extractors': [],
'list_mode': False,
'issue_exclusion_patterns': [
# WordPress admin & system paths
'/wp-admin/*', '/wp-content/plugins/*', '/wp-content/themes/*', '/wp-content/uploads/*',
@@ -300,12 +310,43 @@ class WebCrawler:
]
}
def start_crawl(self, url, user_id=None, session_id=None):
"""Start crawling from the given URL"""
@staticmethod
def normalize_url_list(urls):
"""Clean a pasted URL list: add a scheme where missing, drop
blanks and duplicates, keep the original order."""
cleaned, seen = [], set()
for raw in urls or []:
u = str(raw).strip()
if not u or u.startswith('#'):
continue
if not u.startswith(('http://', 'https://')):
u = 'https://' + u
if urlparse(u).netloc and u not in seen:
seen.add(u)
cleaned.append(u)
return cleaned
def start_crawl(self, url, user_id=None, session_id=None, url_list=None):
"""Start crawling from the given URL.
With ``url_list`` the crawl runs in list mode: exactly those URLs
are fetched and analysed, links are recorded but never followed,
and sitemap discovery is skipped.
"""
if self.is_running:
return False, "Crawl already in progress"
try:
list_urls = None
if url_list is not None:
list_urls = self.normalize_url_list(url_list)
if not list_urls:
return False, "The URL list has no valid URLs"
if len(list_urls) > MAX_LIST_URLS:
return False, f"List mode accepts at most {MAX_LIST_URLS} URLs"
url = list_urls[0]
self.config['list_mode'] = list_urls is not None
# Validate and normalize URL
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
@@ -334,14 +375,15 @@ class WebCrawler:
# Reset state
self._reset_state()
# Add initial URL
self.link_manager.add_url(url, 0)
self.stats['discovered'] = 1
# Seed the queue: the start URL, or the whole list
for seed in (list_urls or [url]):
self.link_manager.add_url(seed, 0)
self.stats['discovered'] = self.link_manager.get_stats()['discovered']
# Discover sitemaps in the background so the crawl (and the UI)
# starts immediately — sitemap probes can take many seconds on
# slow sites and used to block this request until they finished
if self.config.get('discover_sitemaps', True):
# Sitemaps are probed in the background so the crawl
# starts at once; slow sites took seconds per probe.
# List mode fetches only the list, so it skips them.
if self.config.get('discover_sitemaps', True) and not list_urls:
self._sitemap_discovery_done = False
threading.Thread(target=self._discover_sitemaps_background,
args=(url,), daemon=True).start()
@@ -373,6 +415,10 @@ class WebCrawler:
self.link_manager = LinkManager(self.base_domain, event_log=self.event_log)
self.sitemap_parser = SitemapParser(self.session, self.base_domain, self.config['timeout'])
self.issue_detector = IssueDetector(self.config.get('issue_exclusion_patterns', []))
extractor = CustomExtractor(self.config.get('custom_extractors') or [])
for error in extractor.errors:
print(f"Custom extraction rule skipped: {error}")
self.custom_extractor = extractor if extractor else None
# Initialize JS renderer if needed
if self.config.get('enable_javascript', False):
@@ -594,8 +640,11 @@ class WebCrawler:
print(f"Restored queue: {len(self.link_manager.discovered_urls)} pending, "
f"{len(self.link_manager.visited_urls)} visited")
# If queue is empty (no checkpoint or crawl crashed early), rebuild queue from links
if not self.link_manager.discovered_urls:
# If queue is empty (no checkpoint or crawl crashed early),
# rebuild it from links. List mode never follows links.
queue_empty = len(self.link_manager.discovered_urls) == 0
spider_mode = not self.config.get('list_mode')
if queue_empty and spider_mode:
print("Queue is empty - rebuilding from discovered links")
# Get all URLs from loaded links that haven't been crawled yet
@@ -793,9 +842,13 @@ class WebCrawler:
try:
# Get discovered URLs from link manager
# Spider mode caps the checkpoint (links rebuild the
# rest). A list cannot be rebuilt, so keep all of it.
discovered_urls = []
if hasattr(self.link_manager, 'discovered_urls'):
discovered_urls = list(self.link_manager.discovered_urls)[:1000] # Limit to prevent huge checkpoints
discovered_urls = list(self.link_manager.discovered_urls)
if not self.config.get('list_mode'):
discovered_urls = discovered_urls[:1000]
# Get visited URLs
visited_urls = []
@@ -1015,8 +1068,42 @@ class WebCrawler:
else:
return self._crawl_url_with_requests(url, depth)
def _robots_blocked_result(self, url, depth):
"""In list mode, a row for a listed URL robots.txt disallows.
Spider mode filters these before queueing, but a list is seeded
directly, so the check happens at fetch time and the URL still
gets a row saying why it was skipped.
"""
if self.config.get('list_mode') and self.config.get('respect_robots', True):
if self._check_robots_txt(url):
return None
result = self.seo_extractor.create_empty_result(
url, depth, 0, 'Blocked by robots.txt', error_type='blocked_by_robots')
result['is_internal'] = self.link_manager.is_internal(url)
return result
return None
def _apply_custom_extraction(self, soup, raw_html, result):
if self.custom_extractor:
result['custom_extraction'] = self.custom_extractor.extract(soup, raw_html)
def _should_follow_links(self, depth, content_is_internal):
"""Whether a fetched page may seed the queue.
Gated on where the content lives: a page that redirected
off-domain is external content.
"""
if self.config.get('list_mode') or depth >= self.config['max_depth']:
return False
return content_is_internal or self.config['crawl_external']
def _crawl_url_with_requests(self, url, depth):
"""Crawl a single URL using traditional HTTP requests"""
blocked = self._robots_blocked_result(url, depth)
if blocked:
return blocked
print(f"Starting crawl of {url}")
retries = self.config.get('retries', 3)
@@ -1139,6 +1226,7 @@ class WebCrawler:
self.seo_extractor.extract_link_counts(soup, result, self.base_domain)
self.seo_extractor.extract_hreflang(soup, result)
self.seo_extractor.extract_schema_org(soup, result)
self._apply_custom_extraction(soup, response.content, result)
# Collect all links (returns only the ones new to this crawl)
new_links = self.link_manager.collect_all_links(soup, url, self.crawl_results,
@@ -1153,16 +1241,7 @@ class WebCrawler:
if self.db_save_enabled:
self.unsaved_links.extend(new_links)
# Extract links for further crawling. Gate on where the
# content actually lives: a page that redirected off-domain
# is external content and shouldn't seed the queue unless
# external crawling is enabled
should_extract = (
(content_is_internal and depth < self.config['max_depth']) or
(self.config['crawl_external'] and depth < self.config['max_depth'])
)
if should_extract:
if self._should_follow_links(depth, content_is_internal):
self.link_manager.extract_links(soup, url, depth + 1, self._should_crawl_url,
include_images=self.config.get('crawl_images', False),
base_url=final_url)
@@ -1185,7 +1264,9 @@ class WebCrawler:
async def _crawl_url_with_javascript(self, url, depth):
"""Crawl a single URL using JavaScript rendering"""
start_time = time.time()
blocked = self._robots_blocked_result(url, depth)
if blocked:
return blocked
try:
# Render page with JavaScript
@@ -1267,6 +1348,7 @@ class WebCrawler:
self.seo_extractor.extract_link_counts(soup, result, self.base_domain)
self.seo_extractor.extract_hreflang(soup, result)
self.seo_extractor.extract_schema_org(soup, result)
self._apply_custom_extraction(soup, html_content, result)
# Collect all links (returns only the ones new to this crawl)
new_links = self.link_manager.collect_all_links(soup, url, self.crawl_results,
@@ -1281,14 +1363,7 @@ class WebCrawler:
if self.db_save_enabled:
self.unsaved_links.extend(new_links)
# Extract links for further crawling. Gated on
# where the content lives, as in the HTTP path.
should_extract = (
(content_is_internal and depth < self.config['max_depth']) or
(self.config['crawl_external'] and depth < self.config['max_depth'])
)
if should_extract:
if self._should_follow_links(depth, content_is_internal):
self.link_manager.extract_links(soup, url, depth + 1, self._should_crawl_url,
include_images=self.config.get('crawl_images', False),
base_url=final_url)
@@ -1483,6 +1558,11 @@ class WebCrawler:
for l in broken
]
# List mode checks the list itself, so outbound links
# are recorded but left unprobed
if self.config.get('list_mode'):
return
if not self.config.get('crawl_external', False):
external_links = [l for l in new_links
if l.get('placement') != 'image' and not l.get('is_internal')
@@ -1545,7 +1625,10 @@ class WebCrawler:
link['target_status'] = 0
self._head_status_cache[url] = link['target_status']
# Skip synthesis for URLs that will be (or were) crawled for real
# Skip synthesis for URLs crawled for real. List mode
# keeps its rows to exactly the listed URLs.
if self.config.get('list_mode'):
return
if not self._should_crawl_url(url):
self._record_head_result(url, link['target_status'], content_type, size, depth,
link_check_only)
@@ -1639,6 +1722,17 @@ class WebCrawler:
parsed = urlparse(url)
robots_url = f"{parsed.scheme}://{parsed.netloc}/robots.txt"
with self._robots_locks_guard:
host_lock = self._robots_locks.setdefault(robots_url, threading.Lock())
with host_lock:
return self._robots_allows(robots_url, url)
except Exception:
return True
def _robots_allows(self, robots_url, url):
"""Fetch (once) and consult robots.txt; caller holds the host lock"""
try:
if robots_url not in self._robots_cache:
rp = RobotFileParser()
rp.set_url(robots_url)
+19 -2
View File
@@ -47,7 +47,9 @@ class SettingsManager:
'enableJavaScript', 'jsWaitTime', 'jsTimeout', 'jsBrowser', 'jsHeadless',
'jsUserAgent', 'jsViewportWidth', 'jsViewportHeight', 'jsMaxConcurrentPages',
# Custom CSS tab
'customCSS'
'customCSS',
# Extraction tab
'customExtractors'
]
# admin: all settings including Advanced tab
@@ -130,6 +132,10 @@ class SettingsManager:
# Custom CSS styling
'customCSS': '',
# Custom extraction rules: list of
# {name, type: css|xpath, selector, mode, attribute}
'customExtractors': [],
# Issue exclusion patterns
'issueExclusionPatterns': '''# WordPress admin & system paths
/wp-admin/*
@@ -368,6 +374,9 @@ class SettingsManager:
# Only validate the filtered settings that the user is allowed to change
test_settings = {**self.default_settings}
test_settings.update(filtered_settings)
extractor_errors = self.extractor_errors(test_settings.get('customExtractors'))
if extractor_errors:
return False, "Custom extraction: " + "; ".join(extractor_errors)
if not self.validate_settings(test_settings):
return False, "Invalid settings provided"
@@ -415,6 +424,13 @@ class SettingsManager:
fresh_defaults = self._get_default_settings()
return self.save_settings(fresh_defaults)
@staticmethod
def extractor_errors(rules):
"""Problems with the custom extraction rules, as messages"""
from src.core.custom_extractor import normalize_rules
_, errors = normalize_rules(rules if rules is not None else [])
return errors
def validate_settings(self, settings):
"""Validate settings values"""
try:
@@ -514,7 +530,8 @@ class SettingsManager:
'js_max_concurrent_pages': settings['jsMaxConcurrentPages'],
'issue_exclusion_patterns': [p.strip() for p in settings['issueExclusionPatterns'].split('\n') if p.strip()],
'enable_duplication_check': settings['enableDuplicationCheck'],
'duplication_threshold': settings['duplicationThreshold']
'duplication_threshold': settings['duplicationThreshold'],
'custom_extractors': settings.get('customExtractors') or []
}
def _parse_custom_headers(self, headers_text):
+3 -1
View File
@@ -13,7 +13,7 @@ python tests/fixture_tests.py
```
Prints a PASS/FAIL line per behaviour and exits non-zero if any fail. If ports
8911-8923 are taken locally, set `FIXTURE_BASE_PORT` to move the range.
8911-8926 are taken locally, set `FIXTURE_BASE_PORT` to move the range.
Each test pins a bug that reached production once:
@@ -27,6 +27,8 @@ Each test pins a bug that reached production once:
| `test_duplicate_detection_is_linear` | A site of templated pages holds the crawl in "finishing up" for minutes and produces two duplicate issues per matching pair (700k rows for 1,000 pages), locking the database while they save |
| `test_export_formats_apply_to_every_data_type` | The format chosen in Settings is ignored for links/issues exports, or Excel silently produces CSV |
| `test_crawl_delay_is_honoured` | The crawl delay setting is ignored with JavaScript rendering off, so sites get hit as fast as concurrency allows |
| `test_list_mode_fetches_only_the_list` | List mode follows links, probes sitemaps, drops a listed URL, fetches a robots.txt-disallowed URL, or misses URLs on a second site |
| `test_custom_extraction` | CSS/XPath extractors return wrong values, break on pages without matches, lose their per-extractor export columns, or save with an invalid selector |
## crawl_harness.py
+115 -2
View File
@@ -98,7 +98,7 @@ def make_handler(routes, hits=None, slow_paths=(), slow_seconds=0.0):
return Handler
def crawl(url, timeout=120, **config):
def crawl(url, timeout=120, url_list=None, **config):
"""Run a crawl to completion and return the crawler for inspection."""
crawler = WebCrawler()
crawler.config.update({
@@ -108,7 +108,7 @@ def crawl(url, timeout=120, **config):
})
crawler.config.update(config)
ok, message = crawler.start_crawl(url)
ok, message = crawler.start_crawl(url, url_list=url_list)
assert ok, message
deadline = time.time() + timeout
while crawler.is_running and time.time() < deadline:
@@ -639,6 +639,117 @@ def test_crawl_delay_is_honoured():
srv.shutdown()
def test_list_mode_fetches_only_the_list():
"""List mode fetches the listed URLs across any number of sites,
follows no links, skips sitemaps and honours robots.txt."""
site_a, site_b = BASE_PORT + 13, BASE_PORT + 14
a_hits, b_hits = [], []
a = serve(make_handler({
'/robots.txt': 'User-agent: *\nDisallow: /private\n',
'/a': html('<a href="/b">b</a><a href="/c">c</a><img src="/i.png">'),
'/b': html('never listed'),
'/c': html('<a href="/b">b</a>'),
'/private': html('secret'),
'/i.png': png(),
}, hits=a_hits), site_a)
b = serve(make_handler({
'/x': html(f'<a href="http://127.0.0.1:{site_a}/b">b</a>'),
}, hits=b_hits), site_b)
base_a, base_b = f'http://127.0.0.1:{site_a}', f'http://127.0.0.1:{site_b}'
listed = [f'{base_a}/a', f'{base_a}/c', f'{base_b}/x', f'{base_a}/a',
'', f'{base_a}/private', f'{base_a}/missing']
try:
crawler = crawl(listed[0], url_list=listed, respect_robots=True,
discover_sitemaps=True, max_depth=4)
rows = {r['url']: r for r in crawler.crawl_results}
expected = {f'{base_a}/a', f'{base_a}/c', f'{base_b}/x',
f'{base_a}/private', f'{base_a}/missing'}
result('list: one row per listed URL, duplicates and blanks dropped',
set(rows) == expected and len(crawler.crawl_results) == 5,
str(sorted(rows)))
result('list: links are recorded but never followed',
'GET /b' not in a_hits
and any(l['target_url'].endswith('/b') for l in crawler.link_manager.all_links),
str(a_hits))
result('list: pages on a second site are crawled too',
rows.get(f'{base_b}/x', {}).get('status_code') == 200)
result('list: sitemap discovery is skipped',
all('sitemap' not in h for h in a_hits + b_hits), str(a_hits))
private = rows.get(f'{base_a}/private', {})
result('list: robots.txt disallowed URL is reported, not fetched',
private.get('error_type') == 'blocked_by_robots'
and 'GET /private' not in a_hits, str(private.get('error_type')))
result('list: broken listed URL reports its status',
rows.get(f'{base_a}/missing', {}).get('status_code') == 404)
result('list: crawl is flagged as list mode in the config snapshot',
crawler.config.get('list_mode') is True)
empty = WebCrawler()
ok, message = empty.start_crawl('', url_list=['', ' '])
result('list: an empty list is rejected', not ok, message)
finally:
a.shutdown()
b.shutdown()
def test_custom_extraction():
"""CSS and XPath rules pull values from every page, show up as one
export column each, and bad selectors are refused when saving."""
os.environ.setdefault('LOCAL_MODE', 'true')
import main as app_module
from src.settings_manager import SettingsManager
site = BASE_PORT + 15
product = html(
'<h1 class="name">Blue <em>Mug</em></h1>'
'<span class="price" data-currency="EUR"> 9.50 </span>'
'<ul><li class="tag">kitchen</li><li class="tag">gift</li></ul>'
'<a href="/other">other</a>')
srv = serve(make_handler({'/': product, '/other': html('<p>no product</p>')}), site)
rules = [
{'name': 'Name', 'type': 'css', 'selector': 'h1.name', 'mode': 'text'},
{'name': 'Name HTML', 'type': 'css', 'selector': 'h1.name', 'mode': 'inner_html'},
{'name': 'Currency', 'type': 'xpath', 'mode': 'attribute', 'attribute': 'data-currency',
'selector': '//span[@class="price"]'},
{'name': 'Price', 'type': 'xpath', 'selector': 'normalize-space(//span[@class="price"])'},
{'name': 'Tags', 'type': 'xpath', 'selector': '//li[@class="tag"]/text()'},
{'name': 'Tag count', 'type': 'xpath', 'selector': 'count(//li[@class="tag"])'},
]
try:
crawler = crawl(f'http://127.0.0.1:{site}/', custom_extractors=rules)
rows = {r['url'].rsplit('/', 1)[-1]: r for r in crawler.crawl_results}
got = rows.get('', {}).get('custom_extraction', {})
want = {'Name': ['Blue Mug'], 'Name HTML': ['Blue <em>Mug</em>'],
'Currency': ['EUR'], 'Price': ['9.50'], 'Tags': ['kitchen', 'gift'],
'Tag count': ['2']}
result('extract: css and xpath rules return the expected values', got == want, str(got))
other = rows.get('other', {}).get('custom_extraction', {})
result('extract: a page without matches gets empty lists, not errors',
other.get('Name') == [] and other.get('Tag count') == ['0'], str(other))
flat, fields = app_module.flatten_custom_extraction(
crawler.crawl_results, ['url', 'custom_extraction', 'title'])
result('extract: export gets one column per extractor, in rule order',
fields == ['url', 'extract_name', 'extract_name_html', 'extract_currency',
'extract_price', 'extract_tags', 'extract_tag_count', 'title'],
str(fields))
home = next(r for r in flat if r['url'].endswith(f'{site}/'))
result('extract: multiple matches are joined in tabular exports',
home['extract_tags'] == 'kitchen | gift', home['extract_tags'])
manager = SettingsManager(tier='admin')
settings = manager.get_settings()
settings['customExtractors'] = [{'name': 'Bad', 'type': 'xpath', 'selector': '//div['}]
ok, message = manager.save_settings(settings)
result('extract: an invalid XPath is refused with its name',
not ok and '"Bad"' in message, message)
settings['customExtractors'] = rules
ok, message = manager.save_settings(settings)
result('extract: valid rules save', ok, message)
finally:
srv.shutdown()
def _playwright_available():
try:
import playwright # noqa: F401
@@ -659,6 +770,8 @@ TESTS = (
test_export_formats_apply_to_every_data_type,
test_empty_alt_is_not_missing_alt,
test_crawl_delay_is_honoured,
test_list_mode_fetches_only_the_list,
test_custom_extraction,
)
+169
View File
@@ -125,6 +125,175 @@ body {
font-weight: 400;
}
/* Crawl mode toggle (Spider / List) */
.input-label-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 6px;
}
.input-label-row .input-label {
margin-bottom: 0;
}
.mode-toggle {
display: inline-flex;
padding: 2px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid #3a4063;
border-radius: 7px;
}
.mode-btn {
padding: 4px 14px;
border: none;
border-radius: 5px;
background: transparent;
color: #94a3b8;
font-size: 12px;
font-weight: 600;
cursor: pointer;
transition: background 0.15s ease, color 0.15s ease;
}
.mode-btn:hover:not(:disabled) {
color: #f1f5f9;
}
.mode-btn.active {
background: linear-gradient(135deg, #7c3aed, #a855f7);
color: #ffffff;
}
.mode-btn:disabled {
cursor: not-allowed;
opacity: 0.6;
}
.url-list-input {
resize: vertical;
min-height: 96px;
font-family: 'Consolas', 'SF Mono', Monaco, monospace;
font-size: 13px;
line-height: 1.5;
}
.list-input-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 6px;
}
.list-count {
font-size: 12px;
color: #94a3b8;
}
.list-count-over {
color: #f87171;
}
.btn-small {
padding: 6px 12px;
font-size: 12px;
}
.list-upload-btn {
cursor: pointer;
}
/* Custom extraction */
.extraction-empty {
padding: 14px 16px;
margin: 12px;
border: 1px dashed #3a4063;
border-radius: 8px;
color: #94a3b8;
font-size: 13px;
}
.extractor-head,
.extractor-row {
display: grid;
grid-template-columns: 1.1fr 0.8fr 2.4fr 1fr 1fr 32px;
gap: 8px;
align-items: center;
}
.extractor-head {
margin-bottom: 6px;
font-size: 12px;
font-weight: 600;
color: #94a3b8;
}
.extractor-rows {
display: flex;
flex-direction: column;
gap: 8px;
}
.setting-group .extractor-row input[type="text"],
.setting-group .extractor-row select {
padding: 8px 10px;
font-size: 13px;
}
.setting-group .extractor-row select {
padding-right: 28px;
background-position: right 6px center;
}
.setting-group .extractor-row .ex-selector {
font-family: 'Consolas', 'SF Mono', Monaco, monospace;
}
.extractor-row input:disabled {
opacity: 0.4;
}
.ex-remove {
width: 32px;
height: 32px;
border: 1px solid #3a4063;
border-radius: 6px;
background: transparent;
color: #94a3b8;
font-size: 18px;
line-height: 1;
cursor: pointer;
}
.ex-remove:hover {
color: #f87171;
border-color: #f87171;
}
.extractor-actions {
display: flex;
align-items: center;
gap: 12px;
margin-top: 10px;
}
.extractor-error {
color: #f87171;
font-size: 12px;
}
.extract-value {
display: inline-block;
margin: 2px 4px 2px 0;
padding: 1px 6px;
border-radius: 4px;
background: rgba(139, 92, 246, 0.15);
word-break: break-word;
}
.control-buttons {
display: flex;
gap: 8px;
+249 -10
View File
@@ -35,9 +35,17 @@ let virtualScrollers = {
external: null,
internalLinks: null,
externalLinks: null,
issues: null
issues: null,
extraction: null
};
// 'spider' follows links from one URL; 'list' checks a pasted list
let crawlMode = 'spider';
const MAX_LIST_URLS = 100000;
// Extractor names currently shown as Custom Extraction columns
let extractionColumns = [];
// Initialize application
document.addEventListener('DOMContentLoaded', async function() {
await initializeApp();
@@ -166,8 +174,12 @@ async function initializeApp() {
}
}
// Set initial focus
document.getElementById('urlInput').focus();
// Restore the crawl mode picked last time in this browser
let savedMode = 'spider';
try {
savedMode = localStorage.getItem('librecrawl_crawl_mode') || 'spider';
} catch (e) { /* storage unavailable */ }
setCrawlMode(savedMode === 'list' ? 'list' : 'spider');
console.log('LibreCrawl initialized');
}
@@ -181,7 +193,7 @@ function setupEventListeners() {
}
function handleUrlKeypress(event) {
if (event.key === 'Enter' && !crawlState.isRunning) {
if (event.key === 'Enter' && crawlMode === 'spider' && !crawlState.isRunning) {
toggleCrawl();
}
}
@@ -196,7 +208,92 @@ function toggleCrawl() {
}
}
// ---- Crawl mode (Spider / List) ----
function setCrawlMode(mode) {
if (crawlState.isRunning) return;
crawlMode = mode === 'list' ? 'list' : 'spider';
try {
localStorage.setItem('librecrawl_crawl_mode', crawlMode);
} catch (e) { /* storage unavailable */ }
const isList = crawlMode === 'list';
document.querySelectorAll('.mode-btn').forEach(btn => {
const active = btn.dataset.mode === crawlMode;
btn.classList.toggle('active', active);
btn.setAttribute('aria-pressed', active ? 'true' : 'false');
});
document.getElementById('urlInput').style.display = isList ? 'none' : '';
document.getElementById('listInputGroup').style.display = isList ? 'block' : 'none';
const label = document.getElementById('urlInputLabel');
label.textContent = isList ? 'URLs to Check' : 'URL to Crawl';
label.htmlFor = isList ? 'urlListInput' : 'urlInput';
updateListCount();
document.getElementById(isList ? 'urlListInput' : 'urlInput').focus();
}
// Pull URLs out of pasted text or a .txt/.csv file. Accepts one
// URL per line or per CSV cell; header cells and other non-URL
// tokens are skipped. Order is kept, duplicates dropped.
function parseUrlList(text) {
const urls = [];
const seen = new Set();
let skipped = 0;
(text || '').split(/[\s,;]+/).forEach(raw => {
const token = raw.trim().replace(/^["']+|["']+$/g, '');
if (!token || token.startsWith('#')) return;
const looksLikeUrl = /^https?:\/\//i.test(token) ||
/^[^\s\/]+\.[a-z]{2,}(:\d+)?(\/|$)/i.test(token) ||
/^localhost(:\d+)?(\/|$)/i.test(token);
const url = looksLikeUrl ? normalizeUrl(token) : null;
if (!url || !isValidUrl(url)) {
skipped++;
return;
}
if (!seen.has(url)) {
seen.add(url);
urls.push(url);
}
});
return { urls, skipped };
}
function updateListCount() {
const countEl = document.getElementById('urlListCount');
if (!countEl) return;
const { urls, skipped } = parseUrlList(document.getElementById('urlListInput').value);
let text = `${urls.length.toLocaleString()} URL${urls.length === 1 ? '' : 's'}`;
if (skipped) text += ` (${skipped.toLocaleString()} non-URL entr${skipped === 1 ? 'y' : 'ies'} ignored)`;
if (urls.length > MAX_LIST_URLS) text += `, over the ${MAX_LIST_URLS.toLocaleString()} limit`;
countEl.textContent = text;
countEl.classList.toggle('list-count-over', urls.length > MAX_LIST_URLS);
}
function loadUrlListFile(event) {
const file = event.target.files && event.target.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = () => {
const textarea = document.getElementById('urlListInput');
const existing = textarea.value.trim();
textarea.value = existing ? existing + '\n' + reader.result : reader.result;
updateListCount();
showNotification(`Loaded ${file.name}`, 'success');
};
reader.onerror = () => showNotification(`Could not read ${file.name}`, 'error');
reader.readAsText(file);
// Let the same file be picked again after edits
event.target.value = '';
}
function startCrawl() {
if (crawlMode === 'list') {
startListCrawl();
return;
}
const urlInput = document.getElementById('urlInput');
let url = urlInput.value.trim();
@@ -218,6 +315,28 @@ function startCrawl() {
// Update the input field with the normalized URL
urlInput.value = url;
beginCrawl(url, null);
}
function startListCrawl() {
const textarea = document.getElementById('urlListInput');
const { urls } = parseUrlList(textarea.value);
if (urls.length === 0) {
alert('Paste or upload at least one URL to check');
textarea.focus();
return;
}
if (urls.length > MAX_LIST_URLS) {
alert(`List mode accepts up to ${MAX_LIST_URLS.toLocaleString()} URLs; this list has ${urls.length.toLocaleString()}`);
return;
}
beginCrawl(urls[0], urls);
}
// Shared start sequence; urlList is null for a spider crawl
function beginCrawl(url, urlList) {
crawlState.isRunning = true;
crawlState.isPaused = false;
crawlState.startTime = new Date();
@@ -232,14 +351,14 @@ function startCrawl() {
// Update UI
updateCrawlButtons();
showProgress();
updateStatus('Starting crawl...');
updateStatus(urlList ? `Starting list check of ${urlList.length.toLocaleString()} URLs...` : 'Starting crawl...');
// Clear previous data
clearAllTables();
resetStats();
// Start the actual crawling via Python backend
startPythonCrawl(url);
startPythonCrawl(url, urlList);
}
function pauseCrawl() {
@@ -344,25 +463,27 @@ function clearCrawlData() {
document.getElementById('urlInput').focus();
}
function startPythonCrawl(url) {
function startPythonCrawl(url, urlList) {
const payload = urlList ? { url: url, mode: 'list', urls: urlList } : { url: url };
// Call Python backend to start crawling
fetch('/api/start_crawl', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ url: url })
body: JSON.stringify(payload)
})
.then(response => response.json())
.then(data => {
if (data.success) {
updateStatus('Crawling in progress...');
updateStatus(urlList ? 'Checking listed URLs...' : 'Crawling in progress...');
// Refresh user info to update crawl count
loadUserInfo();
// Start polling for updates
pollCrawlProgress();
} else {
updateStatus('Error: ' + data.error);
updateStatus('Error: ' + (data.error || data.message || 'could not start'));
stopCrawl();
}
})
@@ -533,6 +654,10 @@ function overviewUrls() {
// Rebuild the URL virtual scrollers from crawlState.urls, honoring the
// active sidebar filter if one is set
function refreshUrlTables() {
if (isExtractionTabActive()) {
refreshExtractionTable();
}
if (crawlState.filters.active) {
applyFilter(crawlState.filters.active);
return;
@@ -608,6 +733,13 @@ function updateCrawlButtons() {
const saveCrawlBtn = document.getElementById('saveCrawlBtn');
const loadCrawlBtn = document.getElementById('loadCrawlBtn');
// The crawl mode is fixed once a crawl is under way
document.querySelectorAll('.mode-btn').forEach(btn => {
btn.disabled = crawlState.isRunning;
});
const listInput = document.getElementById('urlListInput');
if (listInput) listInput.readOnly = crawlState.isRunning;
if (crawlState.isRunning) {
if (crawlState.isPaused) {
startBtn.innerHTML = `
@@ -788,6 +920,16 @@ function initializeVirtualScrollers() {
console.log('External links virtual scroller initialized');
}
// Custom extraction table (columns follow the extractors)
const extractionContainer = document.querySelector('#extraction-tab .table-container');
if (extractionContainer && extractionContainer.querySelector('tbody')) {
virtualScrollers.extraction = new VirtualScroller(extractionContainer, {
rowHeight: 60,
buffer: 25,
renderRow: renderExtractionRow
});
}
// Issues table
const issuesContainer = document.querySelector('#issues-tab .table-container');
if (issuesContainer && issuesContainer.querySelector('tbody')) {
@@ -808,6 +950,76 @@ function isLinksTabActive() {
return linksTab && linksTab.classList.contains('active');
}
function isExtractionTabActive() {
const tab = document.getElementById('extraction-tab');
return tab && tab.classList.contains('active');
}
// Rows with extraction results; the table only redraws while its
// tab is showing, and catches up when the tab is opened
function refreshExtractionTable() {
const scroller = virtualScrollers.extraction;
if (!scroller) return;
const rows = crawlState.urls.filter(u => u.custom_extraction);
const names = [];
const seen = new Set();
rows.forEach(u => Object.keys(u.custom_extraction).forEach(name => {
if (!seen.has(name)) {
seen.add(name);
names.push(name);
}
}));
if (names.join('\u0000') !== extractionColumns.join('\u0000')) {
extractionColumns = names;
rebuildExtractionHeader();
}
const empty = document.getElementById('extractionEmpty');
if (empty) empty.style.display = rows.length ? 'none' : 'block';
scroller.setData(rows);
}
function rebuildExtractionHeader() {
const headerRow = document.getElementById('extractionHeaderRow');
if (!headerRow) return;
headerRow.innerHTML = '';
['Address', 'Status', ...extractionColumns].forEach(label => {
const th = document.createElement('th');
th.textContent = label;
headerRow.appendChild(th);
});
// Spacer rows span the whole table
const scroller = virtualScrollers.extraction;
if (scroller) {
scroller.topSpacer.firstChild.colSpan = extractionColumns.length + 2;
scroller.bottomSpacer.firstChild.colSpan = extractionColumns.length + 2;
}
if (window.ColumnResizer) {
new ColumnResizer(document.getElementById('extractionTable'));
}
}
function renderExtractionRow(row, urlData) {
const status = urlData.status_code ||
getStatusCodeText(0, urlData.error_type);
row.appendChild(makeTextCell(urlData.url, 'break-all'));
row.appendChild(makeTextCell(status));
const extracted = urlData.custom_extraction || {};
extractionColumns.forEach(name => {
const values = extracted[name] || [];
const full = values.join(' | ');
const shown = full.length > 300 ? full.substring(0, 300) + '…' : full;
const cell = makeTextCell(shown, 'break-word');
if (shown !== full) cell.title = full;
if (values.length > 1) cell.dataset.count = values.length;
row.appendChild(cell);
});
}
function isIssuesTabActive() {
const issuesTab = document.getElementById('issues-tab');
return issuesTab && issuesTab.classList.contains('active');
@@ -1016,6 +1228,15 @@ function clearAllTables() {
if (virtualScrollers.issues) {
virtualScrollers.issues.clear();
}
if (virtualScrollers.extraction) {
virtualScrollers.extraction.clear();
}
if (extractionColumns.length) {
extractionColumns = [];
rebuildExtractionHeader();
}
const extractionEmpty = document.getElementById('extractionEmpty');
if (extractionEmpty) extractionEmpty.style.display = 'block';
// Clear status codes table (not virtualized)
const statusCodesBody = document.getElementById('statusCodesTableBody');
@@ -1095,6 +1316,10 @@ function switchTab(tabName) {
crawlState.pendingLinks = null; // Clear pending data
}
if (tabName === 'extraction') {
refreshExtractionTable();
}
// Load pending issues data if switching to Issues tab
if (tabName === 'issues' && crawlState.pendingIssues) {
updateIssuesTable(crawlState.pendingIssues);
@@ -1485,6 +1710,7 @@ function getStatusCodeText(statusCode, errorType) {
case 'ssl_error': return 'SSL/TLS Error';
case 'connection_error': return 'Connection Error';
case 'file_too_large': return 'Skipped (file too large)';
case 'blocked_by_robots': return 'Blocked by robots.txt';
default: return 'No Response';
}
} else {
@@ -1892,6 +2118,19 @@ function showUrlDetails(url) {
</div>
</div>
${urlData.custom_extraction && Object.keys(urlData.custom_extraction).length ? `
<div class="details-section">
<h4>🧩 Custom Extraction</h4>
<div class="details-grid">
${Object.entries(urlData.custom_extraction).map(([name, values]) => `
<div><strong>${escapeHtml(name)}:</strong> ${(values && values.length)
? values.map(v => `<span class="extract-value">${escapeHtml(v)}</span>`).join(' ')
: '<span style="color:#9ca3af">no match</span>'}</div>
`).join('')}
</div>
</div>
` : ''}
${(urlData.linked_from && urlData.linked_from.length > 0) ? `
<div class="details-section">
<h4>🔗 Linked From</h4>
+142 -2
View File
@@ -58,6 +58,9 @@ let defaultSettings = {
// Custom CSS styling
customCSS: '',
// Custom extraction rules
customExtractors: [],
// Issue exclusion patterns
issueExclusionPatterns: `# WordPress admin & system paths
/wp-admin/*
@@ -350,8 +353,8 @@ function applyTierRestrictions(tier) {
const tierTabs = {
'guest': [], // No settings tabs for guests
'user': ['crawler', 'export', 'issues'],
'extra': ['crawler', 'export', 'issues', 'filters', 'requests', 'customcss', 'javascript'],
'admin': ['crawler', 'requests', 'filters', 'export', 'javascript', 'issues', 'customcss', 'advanced']
'extra': ['crawler', 'export', 'issues', 'filters', 'requests', 'customcss', 'javascript', 'extraction'],
'admin': ['crawler', 'requests', 'filters', 'export', 'javascript', 'extraction', 'issues', 'customcss', 'advanced']
};
const allowedTabs = tierTabs[tier] || [];
@@ -431,6 +434,8 @@ function populateSettingsForm() {
checkbox.checked = currentSettings.exportFields.includes(checkbox.value);
});
renderExtractorRows(currentSettings.customExtractors || []);
// Show/hide proxy settings
const enableProxy = currentSettings.enableProxy;
const proxySettings = document.getElementById('proxySettings');
@@ -485,9 +490,140 @@ function collectSettingsFromForm() {
const exportFieldsCheckboxes = document.querySelectorAll('input[name="exportFields"]:checked');
settings.exportFields = Array.from(exportFieldsCheckboxes).map(cb => cb.value);
settings.customExtractors = collectExtractorRows();
return settings;
}
// ---- Custom extraction rule editor ----
const EXTRACT_MODE_LABELS = {
text: 'Text',
inner_html: 'Inner HTML',
outer_html: 'Outer HTML',
attribute: 'Attribute'
};
function renderExtractorRows(rules) {
const container = document.getElementById('extractorRows');
if (!container) return;
container.innerHTML = '';
(rules.length ? rules : [{}]).forEach(rule => addExtractorRow(rule));
setExtractorError('');
}
function addExtractorRow(rule = {}) {
const container = document.getElementById('extractorRows');
if (!container) return;
const row = document.createElement('div');
row.className = 'extractor-row';
const name = document.createElement('input');
name.type = 'text';
name.className = 'ex-name';
name.placeholder = 'e.g. Price';
name.value = rule.name || '';
const type = document.createElement('select');
type.className = 'ex-type';
[['css', 'CSS'], ['xpath', 'XPath']].forEach(([value, label]) => {
type.add(new Option(label, value, false, (rule.type || 'css') === value));
});
const selector = document.createElement('input');
selector.type = 'text';
selector.className = 'ex-selector';
selector.spellcheck = false;
selector.value = rule.selector || '';
const mode = document.createElement('select');
mode.className = 'ex-mode';
Object.entries(EXTRACT_MODE_LABELS).forEach(([value, label]) => {
mode.add(new Option(label, value, false, (rule.mode || 'text') === value));
});
const attribute = document.createElement('input');
attribute.type = 'text';
attribute.className = 'ex-attribute';
attribute.placeholder = 'e.g. content';
attribute.value = rule.attribute || '';
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'ex-remove';
remove.title = 'Remove extractor';
remove.textContent = '×';
remove.onclick = () => {
row.remove();
if (!container.children.length) addExtractorRow();
};
const sync = () => {
selector.placeholder = type.value === 'xpath'
? "e.g. //span[@class='price']" : 'e.g. .product .price';
attribute.disabled = mode.value !== 'attribute';
};
type.addEventListener('change', sync);
mode.addEventListener('change', sync);
sync();
row.append(name, type, selector, mode, attribute, remove);
container.appendChild(row);
}
function collectExtractorRows() {
return Array.from(document.querySelectorAll('#extractorRows .extractor-row'))
.map(row => ({
name: row.querySelector('.ex-name').value.trim(),
type: row.querySelector('.ex-type').value,
selector: row.querySelector('.ex-selector').value.trim(),
mode: row.querySelector('.ex-mode').value,
attribute: row.querySelector('.ex-attribute').value.trim()
}))
.filter(rule => rule.name || rule.selector);
}
function setExtractorError(message) {
const el = document.getElementById('extractorError');
if (el) el.textContent = message;
}
// Browser-side syntax check for instant feedback. The server
// re-validates with its own parsers (soupsieve, lxml).
function validateExtractors(rules) {
const errors = [];
const seen = new Set();
rules.forEach(rule => {
const label = rule.name || rule.selector;
if (!(rule.name && rule.selector)) {
errors.push(`Extractor "${label}" needs both a name and a selector`);
return;
}
if (seen.has(rule.name)) {
errors.push(`Extractor name "${rule.name}" is used twice`);
}
seen.add(rule.name);
if (rule.mode === 'attribute' && !rule.attribute) {
errors.push(`Extractor "${rule.name}" needs an attribute name`);
}
try {
if (rule.type === 'xpath') {
document.createExpression(rule.selector);
} else {
document.createDocumentFragment().querySelector(rule.selector);
}
} catch (e) {
const kind = rule.type === 'xpath' ? 'XPath' : 'CSS selector';
errors.push(`Extractor "${rule.name}" has an invalid ${kind}`);
}
});
if (rules.length > 30) {
errors.push('At most 30 extractors are allowed');
}
return errors;
}
function saveSettings() {
// Collect settings from form
const newSettings = collectSettingsFromForm();
@@ -655,6 +791,10 @@ function validateSettings(settings) {
errors.push('At least one export field must be selected');
}
const extractorErrors = validateExtractors(settings.customExtractors || []);
setExtractorError(extractorErrors.join('. '));
errors.push(...extractorErrors);
return {
valid: errors.length === 0,
errors: errors
+75 -1
View File
@@ -32,7 +32,15 @@
<section class="url-section">
<div class="url-container">
<div class="input-group">
<label for="urlInput" class="input-label">URL to Crawl</label>
<div class="input-label-row">
<label for="urlInput" class="input-label" id="urlInputLabel">URL to Crawl</label>
<div class="mode-toggle" role="group" aria-label="Crawl mode">
<button type="button" class="mode-btn active" data-mode="spider" onclick="setCrawlMode('spider')"
title="Start from one URL and follow its links">Spider</button>
<button type="button" class="mode-btn" data-mode="list" onclick="setCrawlMode('list')"
title="Check exactly the URLs you paste or upload, without following links">List</button>
</div>
</div>
<input
type="url"
id="urlInput"
@@ -40,6 +48,18 @@
placeholder="https://example.com"
onkeypress="handleUrlKeypress(event)"
>
<div id="listInputGroup" class="list-input-group" style="display: none;">
<textarea id="urlListInput" class="url-input url-list-input" rows="5" spellcheck="false"
placeholder="Paste URLs, one per line&#10;https://example.com/&#10;https://example.com/pricing"
oninput="updateListCount()"></textarea>
<div class="list-input-footer">
<span id="urlListCount" class="list-count">0 URLs</span>
<label class="btn btn-secondary btn-small list-upload-btn">
Upload .txt / .csv
<input type="file" id="urlListFile" accept=".txt,.csv,text/plain,text/csv" onchange="loadUrlListFile(event)" hidden>
</label>
</div>
</div>
</div>
<div class="control-buttons">
<button id="startBtn" class="btn btn-primary" onclick="toggleCrawl()">
@@ -193,6 +213,7 @@
<button class="tab-btn" onclick="switchTab('status-codes')">Status Codes</button>
<button class="tab-btn" onclick="switchTab('links')">Links</button>
<button class="tab-btn" onclick="switchTab('issues')">Issues</button>
<button class="tab-btn" onclick="switchTab('extraction')">Custom Extraction</button>
<button class="tab-btn" onclick="switchTab('pagespeed')">PageSpeed</button>
<button class="tab-btn" onclick="switchTab('visualization')">Visualization</button>
</div>
@@ -398,6 +419,26 @@
</div>
</div>
<div id="extraction-tab" class="tab-pane">
<div id="extractionEmpty" class="extraction-empty">
No custom extraction data yet. Add CSS selector or XPath rules under
<strong>Settings &rsaquo; Extraction</strong>, then start a crawl.
</div>
<div class="table-container">
<table class="data-table" id="extractionTable">
<thead>
<tr id="extractionHeaderRow">
<th>Address</th>
<th>Status</th>
</tr>
</thead>
<tbody id="extractionTableBody">
<!-- Data will be populated here -->
</tbody>
</table>
</div>
</div>
<div id="pagespeed-tab" class="tab-pane">
<div class="pagespeed-container">
<div class="pagespeed-header">
@@ -519,6 +560,7 @@
<button class="settings-tab-btn" onclick="switchSettingsTab('filters')">Filters</button>
<button class="settings-tab-btn" onclick="switchSettingsTab('export')">Export</button>
<button class="settings-tab-btn" onclick="switchSettingsTab('javascript')">JavaScript</button>
<button class="settings-tab-btn" onclick="switchSettingsTab('extraction')">Extraction</button>
<button class="settings-tab-btn" onclick="switchSettingsTab('issues')">Issue Exclusion</button>
<button class="settings-tab-btn" onclick="switchSettingsTab('customcss')">Custom CSS</button>
<button class="settings-tab-btn" onclick="switchSettingsTab('advanced')">Advanced</button>
@@ -798,6 +840,10 @@
<input type="checkbox" name="exportFields" value="robots">
Robots Meta
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="custom_extraction">
Custom Extraction (one column per extractor)
</label>
<label class="checkbox-label">
<input type="checkbox" name="exportFields" value="issues_detected">
Issues Detected (separate export)
@@ -878,6 +924,34 @@
</div>
</div>
<!-- Custom Extraction Settings -->
<div id="extraction-settings" class="settings-tab-content">
<h3>Custom Extraction</h3>
<p class="setting-help">Pull any value out of every crawled HTML page with a CSS selector or an XPath expression: prices, SKUs, authors, publish dates, schema fields, tracking IDs. Each extractor becomes a column in the Custom Extraction tab and in exports.</p>
<div class="setting-group">
<div class="extractor-head">
<span>Name</span><span>Type</span><span>Selector / expression</span><span>Extract</span><span>Attribute</span><span></span>
</div>
<div id="extractorRows" class="extractor-rows"></div>
<div class="extractor-actions">
<button type="button" class="btn btn-secondary btn-small" onclick="addExtractorRow()">+ Add extractor</button>
<span id="extractorError" class="extractor-error" role="alert"></span>
</div>
</div>
<div class="setting-group">
<div style="background: rgba(139, 92, 246, 0.1); border: 1px solid rgba(139, 92, 246, 0.3); border-radius: 6px; padding: 12px; line-height: 1.7;">
<strong>Examples</strong><br>
CSS <code>.product-price</code> with <em>Text</em> reads the visible price<br>
CSS <code>link[rel=alternate]</code> with <em>Attribute</em> <code>hreflang</code> lists hreflang codes<br>
XPath <code>//meta[@property='article:published_time']/@content</code> reads a publish date<br>
XPath <code>count(//a[contains(@href,'/product/')])</code> counts product links<br>
Selectors run on the raw HTML, or on the rendered DOM when JavaScript rendering is on. Up to 50 matches per extractor are kept.
</div>
</div>
</div>
<!-- Issue Exclusion Settings -->
<div id="issues-settings" class="settings-tab-content">
<h3>Issue Exclusion Patterns</h3>