Sure! Below is a Python project that uses Selenium to perform daily Google tasks, optimized for performance and maintainability. The project includes:
- A Python script
daily_tasks.py that automates Google searches and processes results.
- Optimizations such as headless browsing, efficient element selection, and resource cleanup.
- A GitHub Actions workflow file
.github/workflows/daily-run.yml to run the script every 24 hours.
Project Structure
├── daily_tasks.py
└── .github
└── workflows
└── daily-run.yml
daily_tasks.py
#!/usr/bin/env python3
import time
import logging
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
def setup_logging():
logging.basicConfig(level=logging.INFO,
format='[%(asctime)s] %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
def configure_browser():
options = Options()
options.add_argument('--headless') # Run in headless mode for optimization
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(options=options)
return driver
def perform_google_search(driver, query):
logging.info(f"Performing Google search for: {query}")
driver.get('https://www.google.com')
search_box = driver.find_element(By.NAME, 'q')
search_box.clear()
search_box.send_keys(query)
search_box.submit()
time.sleep(2) # Wait for results to load
def process_search_results(driver):
results = driver.find_elements(By.CSS_SELECTOR, 'div.g')
logging.info(f"Found {len(results)} results.")
for index, result in enumerate(results[:5], start=1): # Limit to first 5 results
title_element = result.find_element(By.TAG_NAME, 'h3')
link_element = result.find_element(By.TAG_NAME, 'a')
title = title_element.text
link = link_element.get_attribute('href')
logging.info(f"Result {index}: {title} ({link})")
def main():
setup_logging()
driver = configure_browser()
try:
queries = ["Latest news", "Weather today", "Stock market updates"]
for query in queries:
perform_google_search(driver, query)
process_search_results(driver)
except Exception as e:
logging.error(f"An error occurred: {e}")
finally:
driver.quit() # Ensure the driver is closed to free resources
if __name__ == "__main__":
main()
Code Optimization Details
- Headless Mode: Running Chrome in headless mode reduces resource usage, improving performance.
- Efficient Selectors: Using CSS selectors and limiting results to the first 5 items optimizes data processing.
- Logging: Provides clear logging for easier debugging and monitoring.
- Resource Cleanup: Ensures that the WebDriver is properly closed after execution to free up resources.
GitHub Actions Workflow: .github/workflows/daily-run.yml
name: Daily Run
on:
schedule:
- cron: '0 0 * * *' # Runs every day at 00:00 UTC
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Setup Python
uses: actions/setup-python@v4
with:
python-version: '3.x'
- name: Install Dependencies
run: |
python -m pip install --upgrade pip
pip install selenium webdriver-manager
- name: Run Daily Tasks
run: |
python daily_tasks.py
Workflow Details
- Trigger Schedule: The workflow is scheduled to run every day at midnight UTC.
- Workflow Dispatch: Allows manual triggering of the workflow if needed.
- Environment Setup:
- Checks out the repository code.
- Sets up Python 3.x.
- Installs required Python packages:
selenium and webdriver-manager.
- Run the Script: Executes the
daily_tasks.py script.
Additional Notes
-
WebDriver Manager: To ensure the Chrome WebDriver is up-to-date without manual downloads, you can modify the configure_browser function to use webdriver-manager.
Update configure_browser in daily_tasks.py:
from webdriver_manager.chrome import ChromeDriverManager
def configure_browser():
options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
return driver
Update the dependencies in the workflow:
pip install selenium webdriver-manager
-
Error Handling: The script includes basic exception handling to catch and log errors without stopping the entire process.
-
Scalability: The script is designed to be easily extendable. You can add more queries or expand the process_search_results function to handle different types of Google search results.
Final Remarks
This project provides an optimized and maintainable solution for automating daily Google tasks using Selenium in Python. The use of headless browsing, efficient coding practices, and automated scheduling ensures that the script runs smoothly every 24 hours without manual intervention.
Remember to store any sensitive data (like API keys or personal information) securely if you plan to extend this project. Avoid hardcoding such information in the script or workflow files.
Let me know if you need further assistance or modifications!