PySearXNG
A comprehensive Python library for interacting with SearXNG search instances.
Features
- 🔍 Easy search functionality - Simple API for performing searches
- 🌐 Instance management - Automatic discovery and management of public SearXNG instances
- ⚡ Intelligent failover - Automatically switches to working instances
- 📊 Statistics tracking - Monitor instance performance and success rates
- 🛡️ Rate limiting handling - Built-in protection against rate limits
- 🔧 Highly configurable - Extensive configuration options
- 📦 Multiple export formats - JSON, CSV, and TXT export support
- 🧪 Comprehensive testing - Full test suite included
Installation
# Install the library
pip install -e .
# Install with development dependencies
pip install -e ".[dev]"
Quick Start
Using Public Instances
from pyserxng import SearXNGClient, SearchConfig
from pyserxng.models import SearchCategory
# Initialize the client (uses public instances)
client = SearXNGClient()
# Perform a basic search
results = client.search("Python programming")
print(f"Found {len(results.results)} results")
for result in results.results[:5]:
print(f"- {result.title}: {result.url}")
# Search for images
image_results = client.search_images("cute cats")
# Search for news
news_results = client.search_news("artificial intelligence")
# Custom search configuration
config = SearchConfig(
categories=[SearchCategory.GENERAL],
language="en",
safe_search=SafeSearchLevel.MODERATE,
page=1
)
custom_results = client.search("machine learning", config)
Using Local SearXNG Instance
from pyserxng import LocalSearXNGClient
# Method 1: Simple usage with context manager
with LocalSearXNGClient("http://localhost:8888") as client:
if client.test_connection():
results = client.search("python tutorial")
print(f"Found {len(results.results)} results")
# Method 2: Manual management
client = LocalSearXNGClient("http://localhost:8888")
try:
results = client.search("machine learning")
image_results = client.search_images("nature")
finally:
client.close()
# Method 3: Using regular client with specific instance
from pyserxng import SearXNGClient
from pyserxng.models import InstanceInfo
client = SearXNGClient()
local_instance = InstanceInfo(url="http://localhost:8888")
results = client.search("AI research", instance=local_instance)
Configuration
Environment Variables
You can configure the client using environment variables:
export SEARXNG_DEFAULT_TIMEOUT=15
export SEARXNG_REQUEST_DELAY=1.0
export SEARXNG_EXCLUDE_TOR=true
export SEARXNG_LOG_LEVEL=INFO
Configuration File
Create a configuration file at ~/.pyserxng/config.json:
{
"default_timeout": 15,
"request_delay": 1.0,
"exclude_tor": true,
"log_level": "INFO",
"preferred_countries": ["US", "DE", "FR"],
"min_uptime": 95.0
}
Programmatic Configuration
from pyserxng.config import ClientConfig
config = ClientConfig(
default_timeout=20,
request_delay=2.0,
exclude_tor=True,
min_uptime=95.0
)
client = SearXNGClient(config)
Advanced Usage
Instance Management
# Update instances list
client.update_instances(force=True)
# Get best instances
best_instances = client.get_best_instances(
limit=10,
sort_by="uptime",
min_uptime=95.0,
exclude_countries=["CN", "RU"]
)
# Set specific instance
client.set_instance(best_instances[0])
# Test an instance
is_working = client.test_instance(instance, "test query")
Search Configuration
from pyserxng.models import SearchCategory, SafeSearchLevel, TimeRange
config = SearchConfig(
categories=[SearchCategory.GENERAL, SearchCategory.SCIENCE],
engines=["google", "bing", "duckduckgo"],
language="en",
page=1,
time_range=TimeRange.MONTH,
safe_search=SafeSearchLevel.STRICT,
timeout=30
)
results = client.search("quantum computing", config)
Export Results
from pyserxng.utils import export_search_results
# Export to different formats
export_search_results(results.results, "results.json", "json")
export_search_results(results.results, "results.csv", "csv")
export_search_results(results.results, "results.txt", "txt")
Statistics and Monitoring
# Get client statistics
stats = client.get_stats()
print(f"Total instances: {stats['total_instances']}")
print(f"Working instances: {stats['working_instances']}")
# Instance-specific statistics
for url, instance_stats in stats['instance_stats'].items():
print(f"{url}: {instance_stats.success_rate:.1f}% success rate")
API Reference
SearXNGClient
Main client class for interacting with SearXNG instances.
Methods
search(query, config=None, instance=None)- Perform a searchsearch_images(query, config=None)- Search for imagessearch_videos(query, config=None)- Search for videossearch_news(query, config=None)- Search for newsget_suggestions(query)- Get search suggestionsupdate_instances(force=False)- Update instances listget_instances(**filter_kwargs)- Get filtered instancesget_best_instances(limit=10, **kwargs)- Get best instancesset_instance(instance)- Set specific instancetest_instance(instance, test_query="test")- Test instanceget_stats()- Get client statisticsclose()- Close client and cleanup
Models
SearchResult
title: str- Result titleurl: HttpUrl- Result URLcontent: str- Result descriptionengine: Optional[str]- Search engine usedthumbnail: Optional[HttpUrl]- Thumbnail image URL
InstanceInfo
url: HttpUrl- Instance URLstatus: InstanceStatus- Instance statusuptime: Optional[float]- Uptime percentagecountry: Optional[str]- Country codetls_grade: Optional[str]- TLS security grade
SearchConfig
categories: List[SearchCategory]- Search categorieslanguage: str- Search languagepage: int- Page numbertimeout: int- Request timeoutsafe_search: SafeSearchLevel- Safe search level
Examples
See the examples/ directory for complete usage examples:
basic_usage.py- Basic search functionalityadvanced_config.py- Advanced configuration optionsbatch_search.py- Batch searching multiple queriescustom_instance.py- Using custom instances
Development
Setup Development Environment
# Clone the repository
git clone <repository-url>
cd searxng-client
# Install in development mode
pip install -e ".[dev]"
# Install pre-commit hooks
pre-commit install
Running Tests
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test file
pytest tests/test_client.py
Code Quality
# Format code
black src/ tests/
# Sort imports
isort src/ tests/
# Lint code
flake8 src/ tests/
# Type checking
mypy src/
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Ensure all tests pass (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Acknowledgments
- SearXNG - The awesome metasearch engine
- searx.space - Public instance directory
- All contributors and maintainers of public SearXNG instances
Troubleshooting
Common Issues
No instances available:
- Run
client.update_instances(force=True)to refresh the instance list - Check your internet connection
- Verify the instances API is accessible
Rate limiting errors:
- Increase
request_delayin configuration - Use fewer concurrent requests
- Try different instances
Timeout errors:
- Increase
default_timeoutin configuration - Check instance availability
- Use instances geographically closer to you
Search returns no results:
- Try different search terms
- Check if the instance supports your search category
- Verify the instance is working with
test_instance()
Debug Mode
Enable debug logging to troubleshoot issues:
import logging
logging.basicConfig(level=logging.DEBUG)
# Or set in configuration
config = ClientConfig(log_level="DEBUG")
Metadata
Release files for pyserxng 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| pyserxng-0.1.0.tar.gz | 27.3 kB | Without provenance | Details for pyserxng-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| pyserxng-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for pyserxng-0.1.0-py3-none-any.whl |
Total release size: 52.8 kB
Release files / pyserxng-0.1.0.tar.gz
| Download URL | pyserxng-0.1.0.tar.gz |
|---|---|
| Size | 27.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
1a7f4f4aca84e83a3e2299a8b93f9335be2ad5c5c943cf8d98b72dec7355e1e6
|
|
BLAKE2b-256 checksum How to use checksums |
6ab0c8c34effbb2254f0c3d49e2e631e0d6278b69df073ba0caf35713455f6e5
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.3
|
Release files / pyserxng-0.1.0-py3-none-any.whl
| Download URL | pyserxng-0.1.0-py3-none-any.whl |
|---|---|
| Size | 25.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c14b4989a88e4dd03e261d35f0b0b78917226262e5dda149386c8c8ba32ccc4a
|
|
BLAKE2b-256 checksum How to use checksums |
8c4ca41cb2212072c008437685e06054e51929144530da5fec23f9ea7d58e158
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/6.1.0 CPython/3.13.3
|
Security for pyserxng 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.