Certainly! Below is a comprehensive, optimized Python project that utilizes Selenium to perform daily Google tasks. The project is structured for efficiency, maintainability, and scalability. Additionally, it includes a GitHub Actions workflow to automate the execution every 24 hours.
Table of Contents
- Project Overview
- Project Structure
- Setup Instructions
- Code Implementation
- GitHub Actions Workflow
- Optimization Strategies
- Final Notes
Project Overview
This project automates daily Google search tasks using Selenium in Python. It performs optimized web automation to retrieve and log the top search results for a specified query. The automation is scheduled to run every 24 hours using GitHub Actions, ensuring consistent and reliable execution without manual intervention.
Project Structure
google_daily_tasks/
├── .github/
│ └── workflows/
│ └── daily_google_tasks.yml
├── logs/
│ └── app.log
├── src/
│ ├── __init__.py
│ ├── main.py
│ └── google_tasks.py
├── requirements.txt
└── README.md
.github/workflows/daily_google_tasks.yml: GitHub Actions workflow file to schedule daily execution.
logs/: Directory to store log files.
src/: Contains the Python source code.
main.py: Entry point of the application.
google_tasks.py: Contains the Selenium automation logic.
requirements.txt: Lists Python dependencies.
README.md: Documentation and setup instructions.
Setup Instructions
-
Clone the Repository
git clone https://github.com/yourusername/google_daily_tasks.git
cd google_daily_tasks
-
Set Up a Virtual Environment
It's recommended to use a virtual environment to manage dependencies.
python3 -m venv venv
source venv/bin/activate
-
Install Dependencies
pip install --upgrade pip
pip install -r requirements.txt
-
Run the Script Locally (Optional)
To test the script locally before deploying:
python src/main.py
Code Implementation
1. requirements.txt
List of Python dependencies required for the project.
selenium==4.11.0
webdriver-manager==3.8.6
selenium: Essential for browser automation.
webdriver-manager: Automatically manages browser drivers, ensuring compatibility and reducing manual setup.
2. src/google_tasks.py
Handles the Selenium automation to perform Google searches and extract results.
# src/google_tasks.py
import logging
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
logger = logging.getLogger(__name__)
class GoogleTasks:
def __init__(self, headless=True, implicit_wait=10):
"""
Initialize the Selenium WebDriver with optimized settings.
:param headless: Run browser in headless mode.
:param implicit_wait: Implicit wait time in seconds.
"""
chrome_options = Options()
if headless:
chrome_options.add_argument('--headless')
chrome_options.add_argument('--disable-gpu')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument('--window-size=1920,1080')
# Initialize WebDriver with WebDriver Manager for seamless driver management
self.driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()),
options=chrome_options
)
self.driver.implicitly_wait(implicit_wait)
logger.info("Initialized headless Chrome WebDriver.")
def perform_search(self, query):
"""
Perform a Google search and extract top 5 results.
:param query: The search query string.
:return: List of dictionaries containing rank, title, and link of each result.
"""
try:
self.driver.get('https://www.google.com')
logger.info("Navigated to Google homepage.")
# Handle cookies consent if present
self.handle_cookies_consent()
# Locate the search box, perform the search
search_box = self.driver.find_element(By.NAME, 'q')
search_box.clear()
search_box.send_keys(query)
search_box.submit()
logger.info(f"Performed search for query: '{query}'.")
# Wait for the search results to load
WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.ID, 'search'))
)
logger.info("Search results loaded.")
# Extract top 5 search results
results = self.driver.find_elements(By.CSS_SELECTOR, 'div#search div.g')[:5]
data = []
for idx, result in enumerate(results, start=1):
try:
title = result.find_element(By.TAG_NAME, 'h3').text
link = result.find_element(By.TAG_NAME, 'a').get_attribute('href')
data.append({'rank': idx, 'title': title, 'link': link})
logger.debug(f"Result {idx}: '{title}' - {link}")
except Exception as e:
logger.warning(f"Failed to extract data for result {idx}: {e}")
return data
except Exception as e:
logger.error(f"An error occurred during Google search: {e}")
return []
finally:
self.driver.quit()
logger.info("Closed WebDriver.")
def handle_cookies_consent(self):
"""
Handles the cookies consent popup if it appears.
"""
try:
consent_button = WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, '//div[contains(@class, "VfPpkd-RLmnJb") and text()="I agree"]'))
)
consent_button.click()
logger.info("Accepted cookies consent.")
except Exception:
logger.info("No cookies consent prompt found.")
Key Optimizations:
- Headless Mode: Runs Chrome without a GUI, reducing resource consumption.
- WebDriver Manager: Automatically handles driver downloads and updates.
- Implicit and Explicit Waits: Balances between speed and reliability by waiting only as long as necessary.
- Error Handling: Ensures that the WebDriver is closed properly even if errors occur.
- Logging Levels: Differentiates between info, warning, and error messages for better monitoring.
3. src/main.py
Entry point of the application. Sets up logging and triggers the Google tasks.
# src/main.py
import logging
import os
from datetime import datetime
from google_tasks import GoogleTasks
def setup_logging():
"""
Configures logging to output to both console and a dated log file.
"""
os.makedirs('logs', exist_ok=True)
log_filename = os.path.join('logs', f'app_{datetime.now().strftime("%Y%m%d")}.log')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s',
handlers=[
logging.FileHandler(log_filename),
logging.StreamHandler()
]
)
def main():
"""
Main function to execute Google daily tasks.
"""
setup_logging()
logger = logging.getLogger(__name__)
logger.info("Starting Google daily tasks script.")
# Define the search query
query = "Selenium Python best practices"
# Initialize GoogleTasks
google_tasks = GoogleTasks(headless=True)
# Perform search
results = google_tasks.perform_search(query)
# Process and log results
if results:
for result in results:
logger.info(f"Rank {result['rank']}: {result['title']} - {result['link']}")
else:
logger.warning("No results found or an error occurred during the search.")
logger.info("Google daily tasks script completed.")
if __name__ == '__main__':
main()
Key Features:
- Centralized Logging: Logs both to a file (for persistent records) and the console (for real-time monitoring).
- Modular Design: Separates concerns by delegating web tasks to
google_tasks.py.
- Scalability: Easy to extend with additional tasks or functionalities in the future.
4. README.md
Provides an overview, setup instructions, and usage information.
# Google Daily Tasks Automation with Selenium
This project automates daily Google search tasks using Selenium in Python. It retrieves the top 5 search results for a specified query and logs them for monitoring and analysis.
## Features
- **Automated Google Searches**: Performs searches for predefined queries.
- **Headless Browser Execution**: Efficient and resource-friendly.
- **Robust Logging**: Stores logs both locally and as GitHub Actions artifacts.
- **Scheduled Execution**: Runs automatically every 24 hours using GitHub Actions.
## Setup
### Prerequisites
- Python 3.7 or higher
- GitHub account (for GitHub Actions)
### Installation
1. **Clone the Repository**
```bash
git clone https://github.com/yourusername/google_daily_tasks.git
cd google_daily_tasks
-
Set Up a Virtual Environment
python3 -m venv venv
source venv/bin/activate
-
Install Dependencies
pip install --upgrade pip
pip install -r requirements.txt
Configuration
- Search Query: Modify the
query variable in src/main.py to change the search topic.
Running Locally
python src/main.py
Deploying with GitHub Actions
The project is pre-configured with a GitHub Actions workflow that runs the script daily. Ensure the repository is pushed to GitHub to activate the workflow.
License
MIT License
---
## GitHub Actions Workflow
Automates the execution of the Python script every 24 hours.
### `.github/workflows/daily_google_tasks.yml`
```yaml
# .github/workflows/daily_google_tasks.yml
name: Daily Google Tasks
on:
schedule:
- cron: '0 0 * * *' # Runs every day at 00:00 UTC
workflow_dispatch: # Allows manual triggering
jobs:
run-google-tasks:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v3
- name: Set Up Python
uses: actions/setup-python@v4
with:
python-version: '3.11' # Specify desired Python version
- name: Cache Pip Dependencies
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Run Google Tasks Script
run: |
python src/main.py
- name: Upload Logs as Artifact
if: always()
uses: actions/upload-artifact@v3
with:
name: google_tasks_logs
path: logs/
Workflow Breakdown:
-
Triggering Mechanism
- Scheduled: Executes every day at midnight UTC.
- Manual Dispatch: Allows manual triggering via the GitHub Actions interface.
-
Jobs
-
Environment Setup
- Checks out the repository code.
- Sets up the specified Python version.
- Caches pip dependencies to speed up installation in subsequent runs.
-
Execution
- Installs Python dependencies.
- Runs the main Python script.
-
Artifacts
- Uploads the
logs/ directory as an artifact for review.
Benefits:
- Reliability: Ensures the script runs consistently without manual intervention.
- Visibility: Logs are accessible through GitHub Actions artifacts for auditing and debugging.
- Efficiency: Caching reduces setup time, making the workflow faster.
Optimization Strategies
The project emphasizes optimization across various aspects:
-
Code Efficiency
- Headless Browsing: Eliminates the overhead of rendering UI elements.
- Selective Scraping: Limits data extraction to only necessary elements (top 5 results).
- Graceful Error Handling: Prevents crashes and ensures resources are freed.
-
Dependency Management
- WebDriver Manager: Automatically handles driver compatibility, reducing manual errors.
- Caching in CI/CD: Speeds up GitHub Actions runs by caching pip dependencies.
-
Resource Utilization
- Implicit and Explicit Waits: Balances between speed and reliability, reducing unnecessary delays.
-
Logging and Monitoring
- Dual Logging: Logs to both console and file for real-time and historical analysis.
- Log Rotation: Daily log files prevent oversized logs and facilitate organization.
-
Scalability and Maintainability
- Modular Codebase: Separates concerns, making it easier to extend or modify functionalities.
- Documentation: Comprehensive
README.md ensures ease of understanding and onboarding.
Final Notes
This project serves as a robust template for automating web-based tasks using Selenium and scheduling them using GitHub Actions. Its optimized structure ensures efficient execution, reliable performance, and ease of maintenance. You can extend this foundation to incorporate more complex tasks, integrate with databases, or expand logging and notification mechanisms as needed.
Feel free to customize the search queries, expand the data extraction logic, or integrate additional features to suit your specific requirements.
Happy Automating! 🚀