Skip to content
PStarHPublic

About

A Search Engine using scraper where the User can get search result from multiple search engine and add their own ones. The search result is sorted with NLP algorithm

Resources

Stars

64 stars

Watchers

6 watching

Forks

Repository files navigation

MSTSearch

CI License: MIT

MSTSearch is an experimental metasearch aggregator: it scrapes result pages from several engines, normalizes and deduplicates them, then ranks the combined list with BM25, TF-IDF cosine similarity and Word2Vec cosine similarity. A small Vue 3 frontend displays the ranked results and can display an optional LLM summary.

The ranking pipeline runs completely offline against bundled fixtures, so you can verify the core behavior without scraping the live web.

Status: experimental. The offline demo and ranking pipeline are tested in CI. The live scrapers are best-effort, depend on third-party HTML that changes often, and are not exercised by CI. Read Scraping disclaimer before running them.

Contents

Quickstart

Requires Python 3.11 or 3.12. The offline demo does not need Chrome or network access after dependencies are installed.

python3.12 -m venv .venv && . .venv/bin/activate && pip install -r requirements.txt && python -m backend.cli --demo

On Windows, create/activate the environment with py -3.12 -m venv .venv and .venv\Scripts\activate instead of the source portion.

Example output (trimmed; exact scores depend on dependency versions):

MSTSearch offline demo (no network access)
Query: python web scraping
Fixture results: 9 | after cleaning: 5 | ranked: 5

 1. 100.00  [Bing] Python Web Scraping: A Practical Guide
    https://example.com/guides/python-web-scraping
 2.  78.71  [Quark] Scrapy: build a maintainable web scraper
    https://example.net/scrapy-web-scraper
 3.  49.36  [Sogou] Beautiful Soup tutorial: parse HTML with Python
    https://example.org/beautiful-soup-tutorial
 4.  12.63  [mso] Weather forecast for Shanghai
    https://example.com/weather/shanghai
 5.   5.22  [Sohu] Easy weeknight cooking recipes
    https://example.com/food/weeknight-recipes

Useful demo flags:

python -m backend.cli --demo --query "cooking recipes"
python -m backend.cli --demo --json
python -m backend.cli --demo --fixture path/to/results.json --limit 5

The demo fixture lives at backend/fixtures/demo_results.json. It deliberately contains tracking parameters, a duplicate URL, an invalid URL and a javascript: URL so cleaning and deduplication are visible.

What works

Area State
Offline cleaning, deduplication, ranking, CLI demo Working, unit-tested
Flask /search API Working when the target engine is reachable
Live scrapers (Bing, Sogou, Quark, MSO via HTTP) Best-effort; markup-dependent
Live scrapers (Baidu, Sohu via Selenium) Best-effort; require Chrome
Optional LLM summaries Works with any OpenAI-compatible chat endpoint; disabled without an API key
Vue 3 frontend Functional local UI; settings are not persisted
Authentication, persistence, production deployment Not implemented

Architecture

SearchPage.vue --POST /search--> Flask
                                   |
                                   +--> engine scrapers (requests/Selenium)
                                   |      Bing, Baidu, Sogou, Sohu, Quark, MSO
                                   |
                                   +--> JsonCleaner
                                   |      text normalization, URL canonicalization,
                                   |      invalid-row removal, URL deduplication,
                                   |      optional page-content enrichment
                                   |
                                   +--> Sort
                                   |      BM25 + TF-IDF cosine + Word2Vec cosine
                                   |
                                   +--> ranked JSON --> Vue results page
                                                         |
                                                         +--POST /summarize--> optional LLM

The default cleaning path is offline. It only fetches article pages when MSTSEARCH_FETCH_PAGE_CONTENT=1, because that is slow and has privacy/SSRF implications.

Ranking

For each result, the ranker blends three signals:

Signal Weight Notes
BM25 0.45 rank_bm25 over jieba tokens of title + snippet
TF-IDF cosine 0.35 scikit-learn vectors; cosine similarity to the query
Word2Vec cosine 0.20 trained per query on the candidate results; deterministic seed

Each component is normalized to [0, 1] by its maximum, and the final score is 100 * (0.45*bm25 + 0.35*tfidf + 0.20*word2vec). Higher is better.

The original implementation used 1 - cosine_similarity(...) for the Word2Vec component, which is a cosine distance. That inverted the signal: unrelated documents could receive higher scores. The current code returns cosine similarity directly, and tests/test_ranking.py asserts that identical vectors score 1.0, orthogonal vectors score 0.0, and identical text outranks unrelated text. Negative cosine values are clamped to zero only when the component is normalized for fusion; the raw cosine score is still correct.

This is a heuristic ranker, not a validated information-retrieval system. There is no relevance benchmark, and Word2Vec trained on a handful of result snippets is weak. Treat the numeric score as an ordering aid, not a calibrated quality measure.

Configuration

All settings are optional for the offline demo.

Variable Default Purpose
MSTSEARCH_LLM_API_KEY unset Enables /summarize; no key means no summaries
MSTSEARCH_LLM_MODEL gpt-4o-mini Model name passed to the compatible endpoint
MSTSEARCH_LLM_BASE_URL https://api.openai.com/v1 OpenAI-compatible API base, e.g. a local gateway
MSTSEARCH_FETCH_PAGE_CONTENT off Set to 1 to fetch and extract article text for empty snippets
CHROMEDRIVER auto Optional explicit ChromeDriver path; otherwise Selenium Manager resolves it
PORT 5000 Flask listen port
FLASK_DEBUG off Set to 1 for Flask debug mode (local development only)

Optional LLM summaries

backend/summarizer.py speaks the common OpenAI-compatible POST {base_url}/chat/completions protocol. It does not import LangChain or a provider-specific SDK. Configure it server-side:

export MSTSEARCH_LLM_API_KEY="..."
export MSTSEARCH_LLM_MODEL="gpt-4o-mini"
# export MSTSEARCH_LLM_BASE_URL="http://localhost:11434/v1"  # local gateway example
python -m backend.app

If no key is configured, /summarize returns HTTP 200 with {"status": "unavailable", "summary": null} and a message. It never fabricates a summary or silently retries with a different model. Search excerpts are sent to the configured provider; do not enable this for content that must stay local. The prompt treats excerpts as untrusted data, but prompt-injection defenses are not guaranteed.

API

Start the backend from the repository root:

python -m backend.app

Health check:

curl -s http://127.0.0.1:5000/healthz
# {"status":"ok"}

Search (this performs live scraping):

curl -s -X POST http://127.0.0.1:5000/search \
  -H 'Content-Type: application/json' \
  -d '{"keyword":"python web scraping","search_engines":[{"name":"Bing","resultsCount":5}]}'

resultsCount is capped at 50, and engines with resultsCount <= 0 are skipped. Quark and MSO apply lower per-engine caps (13 and 7 results). A custom engine may include a url; unsupported names without a URL are ignored. The response is {"status":"success","results":[...]}. Search results are cached in memory for five minutes and rate-limited to 10 requests/minute per client.

Summarize ranked results:

curl -s -X POST http://127.0.0.1:5000/summarize \
  -H 'Content-Type: application/json' \
  -d '{"question":"What is the main topic?","results":[{"title":"A result","content":"Some text","URL":"https://example.com"}]}'

Without MSTSEARCH_LLM_API_KEY, the response is an honest unavailable status. With a key, provider errors return HTTP 502 rather than a fake answer.

Docker

The image contains the Flask API and the offline demo, but not Chrome or ChromeDriver, so the Selenium engines (Baidu, Sohu) will return no results. HTTP-based scrapers still work if the container has network access.

docker build -t mstsearch .
docker run --rm -p 5000:5000 mstsearch
curl -s http://127.0.0.1:5000/healthz
# Run the offline demo inside the image:
docker run --rm mstsearch python -m backend.cli --demo

For summaries, pass the server-side key at runtime:

docker run --rm -p 5000:5000 -e MSTSEARCH_LLM_API_KEY="..." mstsearch

Frontend

cd frontend
npm install
npm run serve

The frontend runs at http://localhost:8080 and calls the API at http://127.0.0.1:5000 by default. Set VUE_APP_API_BASE to point it at a different backend:

VUE_APP_API_BASE=http://localhost:8000 npm run serve

Search-engine additions/removals are kept in memory only, so they reset when you leave or reload the page. Summaries use the server-side key; the UI does not ask for or store an API key.

Tests and CI

python -m pip install -r requirements-dev.txt
python -m pytest -q

The suite is network-free: an autouse fixture blocks socket connections. Tests cover text cleaning, URL normalization, deduplication, ranking fusion, the Word2Vec similarity direction, the Flask search endpoint with scraper output stubbed, the offline demo, the CLI, and the disabled summarizer path. GitHub Actions runs the suite and the demo on Python 3.11 and 3.12, then builds the frontend with Node.js 20 (.github/workflows/ci.yml).

Live scraping is intentionally not tested in CI: it needs a browser and depends on third-party sites.

Project layout

.
├── backend/
│   ├── app.py               Flask API
│   ├── cli.py               offline demo entrypoint
│   ├── demo.py              fixture-driven pipeline
│   ├── process_result.py    cleaning, URL canonicalization, deduplication
│   ├── sort.py              BM25 / TF-IDF / Word2Vec ranking
│   ├── summarizer.py        optional OpenAI-compatible summary client
│   ├── crawler.py           requests-based scrapers
│   ├── BaiduCrawler.py      Selenium scraper
│   ├── SohuCrawler.py       Selenium scraper
│   └── fixtures/
│       └── demo_results.json
├── tests/                   pytest suite (network blocked)
├── frontend/                Vue 3 + Vue CLI app
├── .github/workflows/ci.yml
├── requirements.txt
├── requirements-dev.txt
├── Dockerfile
├── .dockerignore
└── pytest.ini

Scraping disclaimer

The live scrapers automate third-party search engines. They can break whenever a site changes its HTML, and automated access may violate a site's terms of service, robots policy or local law. You are responsible for how you use them.

  • Use low request counts and respect rate limits, robots policies and applicable terms. The project does not implement CAPTCHA solving, proxy rotation or other anti-blocking evasion.
  • Do not run this as a public search service without adding authentication, egress controls, a proper rate-limit store and legal review.
  • Scraped snippets and page content may be copyrighted; do not redistribute it.
  • Baidu and Sohu use Selenium and need a local Chrome installation. No browser drivers are committed to this repository; Selenium Manager downloads a matching driver at runtime (which requires network access).
  • MSTSEARCH_FETCH_PAGE_CONTENT=1 makes the server request arbitrary result URLs. Keep it off on untrusted deployments: it creates an SSRF surface. Custom engine URLs have the same consideration.

Known limitations

  • Live scraping is fragile and unverified in CI; selectors for Baidu, Sohu, Sogou, Quark and MSO may be stale.
  • Sogou/Quark/MSO results often have title-only snippets; ranking quality depends on snippets or the optional page fetch.
  • Word2Vec is trained on the current candidate set, so its contribution is noisy on small result sets. There is no offline relevance benchmark.
  • The frontend has no authentication or persistence. Search-engine settings are lost when leaving the page or reloading, and there is no saved-result history.
  • The limiter and cache use in-process memory; multiple workers do not share them.
  • Summaries require an external provider and are disabled by default. No summary is produced when the key is missing or the provider fails.
  • The project is not hardened for public deployment.

License

MIT. See LICENSE.

About

A Search Engine using scraper where the User can get search result from multiple search engine and add their own ones. The search result is sorted with NLP algorithm

Resources

Stars

64 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages