A Python package for searching YouTube by keywords
Project description
๐ PyTubeSearch
๐ฅ A powerful Python package for searching YouTube content by keywords. ๐
๐ Built for developers, optimized for performance ใ
โจ Features
- ๐ฏ Keyword Search: Search YouTube videos, channels, playlists by keywords
- ๐น Video Details: Get comprehensive video information including metadata
- ๐ Playlist Support: Extract playlist contents and metadata
- ๐บ Channel Information: Retrieve channel details and content
- ๐ฉณ YouTube Shorts: Access YouTube Shorts content
- ๐ Pagination: Handle large result sets with next page functionality
- ๐ Fast & Reliable: Built with httpx for high performance
- ๐ง Type Safe: Full Pydantic model support with type hints
- ๐๏ธ Flexible Options: Filter by content type (video, channel, playlist, movie)
๐ฆ Installation
pip install pytubesearch
Development Installation
git clone https://github.com/Malith-Rukshan/PyTubeSearch.git
cd PyTubeSearch
pip install -e .
๐ Quick Start
Basic Search
from pytubesearch import PyTubeSearch
# Initialize the client
client = PyTubeSearch()
# Search for videos
results = client.search("python programming")
# Display results
for item in results.items:
print(f"Title: {item.title}")
print(f"Channel: {item.channel_title}")
print(f"Video ID: {item.id}")
print("-" * 50)
# Close the client
client.close()
Using Context Manager
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
results = client.search("machine learning", limit=10)
for video in results.items:
if video.type == "video":
print(f"๐น {video.title} by {video.channel_title}")
Advanced Search with Filters
from pytubesearch import PyTubeSearch, SearchOptions
with PyTubeSearch() as client:
# Search only for videos
video_options = [SearchOptions(type="video")]
results = client.search("python tutorial", options=video_options, limit=5)
# Search only for channels
channel_options = [SearchOptions(type="channel")]
channels = client.search("tech channels", options=channel_options, limit=3)
# Search with playlists included
playlist_results = client.search("programming courses", with_playlist=True)
Get Video Details
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
# Get detailed video information
video_details = client.get_video_details("dQw4w9WgXcQ")
print(f"Title: {video_details.title}")
print(f"Channel: {video_details.channel}")
print(f"Description: {video_details.description}")
print(f"Keywords: {video_details.keywords}")
print(f"Is Live: {video_details.is_live}")
# Get suggested videos
for suggestion in video_details.suggestion:
print(f"Suggested: {suggestion.title}")
Pagination
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
# Get first page
results = client.search("data science")
# Process first page
for item in results.items:
print(f"Page 1: {item.title}")
# Get next page
if results.next_page.next_page_token:
next_results = client.next_page(results.next_page)
for item in next_results.items:
print(f"Page 2: {item.title}")
Playlist Operations
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
# Get playlist contents
playlist = client.get_playlist_data("PLrAXtmRdnEQy9j4XPpPNJkr0bO8E4BcJj")
print(f"Playlist has {len(playlist.items)} videos")
for video in playlist.items:
print(f"๐ฅ {video.title}")
print(f" Channel: {video.channel_title}")
Channel Information
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
# Get channel information
channel_data = client.get_channel_by_id("UC8butISFwT-Wl7EV0hUK0BQ")
for tab in channel_data:
print(f"Tab: {tab.title}")
YouTube Shorts
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
# Get YouTube Shorts
shorts = client.get_short_videos()
for short in shorts:
print(f"๐ฉณ {short.title}")
print(f" ID: {short.id}")
Homepage Suggestions
from pytubesearch import PyTubeSearch
with PyTubeSearch() as client:
# Get homepage suggestions
suggestions = client.get_suggestions(limit=10)
for video in suggestions:
print(f"๐ก {video.title}")
print(f" Channel: {video.channel_title}")
๐ก More Examples: Check out the examples/ directory for additional usage patterns and advanced implementations.
๐ API Reference
PyTubeSearch Class
Methods
search(keyword, with_playlist=False, limit=0, options=None): Search YouTube contentnext_page(next_page_data, with_playlist=False, limit=0): Get next page of resultsget_video_details(video_id): Get detailed video informationget_playlist_data(playlist_id, limit=0): Get playlist contentsget_channel_by_id(channel_id): Get channel informationget_suggestions(limit=0): Get homepage suggestionsget_short_videos(): Get YouTube Shorts
Models
SearchResult: Contains search results and pagination dataSearchItem: Individual search result itemVideoDetails: Detailed video informationPlaylistResult: Playlist contents and metadataChannelResult: Channel informationShortVideo: YouTube Shorts dataSearchOptions: Search filtering options
๐ ๏ธ Development Guide
Setting Up Development Environment
-
Clone the repository:
git clone https://github.com/Malith-Rukshan/PyTubeSearch.git cd PyTubeSearch
-
Create a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activate
-
Install development dependencies:
# Option 1: Using Makefile (recommended) make install-dev # Option 2: Manual installation pip install -e . pip install -r requirements/dev.txt pre-commit install
Development Commands
The project includes a Makefile with common development tasks:
# Install for development
make install-dev
# Run tests
make test
# Run all tests including integration tests
make test-all
# Format code
make format
# Run linting
make lint
# Type checking
make type-check
# Security checks
make security
# Run all checks
make check
# Clean build artifacts
make clean
# Build package
make build
# Upload to Test PyPI
make upload-test
Testing
The project uses pytest for testing with multiple test categories:
-
Unit Tests: Fast tests that don't require network access
pytest tests/ -m "not integration"
-
Integration Tests: Tests that interact with real YouTube data
pytest tests/ -m "integration"
-
All Tests with Coverage:
pytest tests/ --cov=pytubesearch --cov-report=html
Code Quality Standards
- Code Formatting: Black with 100 character line length
- Import Sorting: isort with Black profile
- Linting: Flake8 with custom configuration
- Type Checking: mypy for static type analysis
- Security: Bandit and Safety for security checks
Pre-commit Hooks
The project uses pre-commit hooks to ensure code quality:
# Install pre-commit hooks
pre-commit install
# Run hooks manually
pre-commit run --all-files
Project Structure
PyTubeSearch/
โโโ pytubesearch/ # Main package
โ โโโ __init__.py # Package initialization
โ โโโ client.py # Main client implementation
โ โโโ models.py # Pydantic models
โโโ tests/ # Test suite
โ โโโ conftest.py # Test configuration
โ โโโ test_client.py # Client tests
โ โโโ test_models.py # Model tests
โ โโโ test_integration.py # Integration tests
โโโ examples/ # Usage examples
โโโ requirements/ # Dependency management
โ โโโ base.txt # Core dependencies
โ โโโ dev.txt # Development dependencies
โ โโโ test.txt # Testing dependencies
โโโ .github/workflows/ # CI/CD workflows
โโโ docs/ # Documentation
โโโ ... # Configuration files
Contributing Guidelines
-
Fork the repository and create your feature branch:
git checkout -b feature/amazing-feature
-
Make your changes following the code quality standards
-
Add tests for your changes:
- Unit tests for new functionality
- Integration tests if applicable
- Ensure all tests pass
-
Update documentation if needed:
- Update README.md for new features
- Add docstrings to new functions/classes
- Update examples if applicable
-
Run quality checks:
make check # Runs linting, type checking, and tests
-
Commit your changes:
git commit -m "Add amazing feature"
-
Push to your fork and create a Pull Request
Release Process
- Update version in
pyproject.tomland__init__.py - Update CHANGELOG.md with new features and fixes
- Create a git tag:
git tag -a v1.0.0 -m "Release version 1.0.0" git push origin v1.0.0
- GitHub Actions will automatically build and publish to PyPI
Testing with Test PyPI
Before releasing to PyPI, test the package on Test PyPI:
# Build and upload to Test PyPI
make build
make upload-test
# Install from Test PyPI to test
pip install --index-url https://test.pypi.org/simple/ pytubesearch
Debugging
For debugging integration tests or development:
# Enable debug logging
export PYTUBESEARCH_DEBUG=1
# Run specific test with verbose output
pytest tests/test_integration.py::TestSearchIntegration::test_basic_search_integration -v -s
Dependencies Management
The project uses a multi-file requirements approach:
requirements/base.txt: Core runtime dependenciesrequirements/dev.txt: Development tools and utilitiesrequirements/test.txt: Testing framework and tools
To update dependencies:
- Edit the appropriate requirements file
- Test the changes locally
- Update version constraints if needed
๐ง Configuration
Timeout Settings
from pytubesearch import PyTubeSearch
# Set custom timeout (default: 30 seconds)
client = PyTubeSearch(timeout=60.0)
Error Handling
from pytubesearch import PyTubeSearch, PyTubeSearchError
try:
with PyTubeSearch() as client:
results = client.search("programming")
except PyTubeSearchError as e:
print(f"Search failed: {e}")
๐ Requirements
- Python 3.8+
- httpx >= 0.24.0
- pydantic >= 2.0.0
๐ ๏ธ Development
Setup Development Environment
git clone https://github.com/Malith-Rukshan/PyTubeSearch.git
cd PyTubeSearch
pip install -e ".[dev]"
Running Tests
pytest tests/
Code Formatting
black pytubesearch/
isort pytubesearch/
Type Checking
mypy pytubesearch/
๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some 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.
โ ๏ธ Disclaimer
This package is for educational purposes only. Please respect YouTube's Terms of Service and robots.txt when using this package. The package author is not responsible for any misuse of this tool.
๐ Acknowledgments
- YouTube for providing the platform
- The Python community for amazing tools and libraries
๐ Support and Community
If you found this project helpful, please give it a โญ on GitHub. This helps more developers discover the project! ๐ซถ
๐ฌ Contact
If you have any questions, feedback, or just want to say hi, you can reach out to me:
- Email: hello@malith.dev
- GitHub: @Malith-Rukshan
๐งโ๐ป Built with ๐ by Malith Rukshan
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 pytubesearch-1.0.0.tar.gz.
File metadata
- Download URL: pytubesearch-1.0.0.tar.gz
- Upload date:
- Size: 30.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6d448a252d317868634bbf2b80b2839bada412d421c3063a62009b7fff7747e6
|
|
| MD5 |
f6e24202f2ccabe30c57cd0946d18116
|
|
| BLAKE2b-256 |
8c91d2fac56780b4d32f80fdecfa9e3fa5ea78cead03ce3948623872c3169c25
|
File details
Details for the file pytubesearch-1.0.0-py3-none-any.whl.
File metadata
- Download URL: pytubesearch-1.0.0-py3-none-any.whl
- Upload date:
- Size: 14.5 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
a27f7fb032598209382dfad76cbd8da27e418575d2bb9f612525837e221290c5
|
|
| MD5 |
016b7617a9db0f37cb1cab1327dec3c3
|
|
| BLAKE2b-256 |
653f3aa101afe10ff796024ff374dcaacab8dd9ef2b4b1f99b7313689179d261
|