Python client library for SearXNG search instances
Project description
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")
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file pyserxng-0.1.0.tar.gz.
File metadata
- Download URL: pyserxng-0.1.0.tar.gz
- Upload date:
- Size: 27.3 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
1a7f4f4aca84e83a3e2299a8b93f9335be2ad5c5c943cf8d98b72dec7355e1e6
|
|
| MD5 |
0875734948e935ed2dc0b0eef62d127e
|
|
| BLAKE2b-256 |
6ab0c8c34effbb2254f0c3d49e2e631e0d6278b69df073ba0caf35713455f6e5
|
File details
Details for the file pyserxng-0.1.0-py3-none-any.whl.
File metadata
- Download URL: pyserxng-0.1.0-py3-none-any.whl
- Upload date:
- Size: 25.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.13.3
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
c14b4989a88e4dd03e261d35f0b0b78917226262e5dda149386c8c8ba32ccc4a
|
|
| MD5 |
75d6e6eb61a1c4440191e682537de786
|
|
| BLAKE2b-256 |
8c4ca41cb2212072c008437685e06054e51929144530da5fec23f9ea7d58e158
|