below code we update logic extract result , from google very details url, image , video , 
2024-10-19 23:29:45,831 [INFO] ====== WebDriver manager ======
2024-10-19 23:29:48,170 [INFO] Get LATEST chromedriver version for google-chrome
2024-10-19 23:29:48,235 [INFO] Get LATEST chromedriver version for google-chrome
2024-10-19 23:29:48,266 [INFO] Driver [C:\Users\heman\.wdm\drivers\chromedriver\win64\129.0.6668.100\chromedriver-win32/chromedriver.exe] found in cache

DevTools listening on ws://127.0.0.1:58714/devtools/browser/b3436c11-70ec-4bec-a908-b9a93ec5bb03
2024-10-19 23:29:49,428 [INFO] WebDriver initialized successfully.
2024-10-19 23:29:50,448 [INFO] Navigated to https://www.google.com/search?q=OpenAI+ChatGPT
Created TensorFlow Lite XNNPACK delegate for CPU.
2024-10-19 23:30:00,825 [ERROR] Timeout occurred: Message: 
Stacktrace:
        GetHandleVerifier [0x00DB5523+24195]
        (No symbol) [0x00D4AA04]
        (No symbol) [0x00C42093]
        (No symbol) [0x00C86ED2]
        (No symbol) [0x00C8711B]
        (No symbol) [0x00CC76F2]
        (No symbol) [0x00CAAB84]
        (No symbol) [0x00CC5280]
        (No symbol) [0x00CAA8D6]
        (No symbol) [0x00C7BA27]
        (No symbol) [0x00C7C43D]
        GetHandleVerifier [0x0107CE13+2938739]
        GetHandleVerifier [0x010CEC69+3274185]
        GetHandleVerifier [0x00E409C2+594722]
        GetHandleVerifier [0x00E47EDC+624700]
        (No symbol) [0x00D537CD]
        (No symbol) [0x00D50528]
        (No symbol) [0x00D506C5]
        (No symbol) [0x00D42CA6]
        BaseThreadInitThunk [0x76D85D29+25]
        RtlInitializeExceptionChain [0x77A7D80B+107]
        RtlGetAppContainerNamedObjectPath [0x77A7D791+561]

2024-10-19 23:30:03,037 [INFO] WebDriver closed.
2024-10-19 23:30:03,037 [ERROR] Failed to retrieve search results.
2024-10-19 23:30:07,117 [WARNING] Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000002353451D2B0>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')': /session/8523b80edf9f28f01b2fad56c18eca2d
2024-10-19 23:30:11,172 [WARNING] Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000002353451D760>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')': /session/8523b80edf9f28f01b2fad56c18eca2d
2024-10-19 23:30:15,257 [WARNING] Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000002353451D970>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it')': /session/8523b80edf9f28f01b2fad56c18eca2d
2024-10-19 23:30:23,357 [INFO] WebDriver closed.

code
import logging
import os
import sys
import time
from dataclasses import dataclass, field
from typing import List, Optional

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import (
    TimeoutException,
    WebDriverException,
    NoSuchElementException,
)
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.file_detector import LocalFileDetector
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager


# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[logging.StreamHandler(sys.stdout)],
)


@dataclass
class SearchResult:
    query: str
    urls: List[str] = field(default_factory=list)
    image_urls: List[str] = field(default_factory=list)
    video_urls: List[str] = field(default_factory=list)


class AdvancedSearchTool:
    """A tool to perform advanced searches and handle file uploads/downloads."""

    def __init__(
        self,
        headless: bool = True,
        wait_time: int = 10,
        download_dir: Optional[str] = None,
    ) -> None:
        """
        Initialize the AdvancedSearchTool.

        Args:
            headless (bool): Run browser in headless mode.
            wait_time (int): Maximum wait time for page elements to load.
            download_dir (Optional[str]): Directory to save downloaded files.
        """
        self.headless = headless
        self.wait_time = wait_time
        self.download_dir = download_dir or os.path.join(os.getcwd(), "downloads")
        os.makedirs(self.download_dir, exist_ok=True)
        self.driver = self._init_webdriver()

    def _init_webdriver(self) -> webdriver.Chrome:
        """Initialize the Selenium WebDriver with specified options."""
        options = Options()
        if self.headless:
            options.add_argument("--headless")
        options.add_argument("--disable-gpu")
        options.add_argument("--no-sandbox")
        options.add_argument("--window-size=1920,1080")
        prefs = {
            "download.default_directory": self.download_dir,
            "download.prompt_for_download": False,
            "download.directory_upgrade": True,
            "safebrowsing.enabled": True,
        }
        options.add_experimental_option("prefs", prefs)

        try:
            service = ChromeService(ChromeDriverManager().install())
            driver = webdriver.Chrome(
                service=service,
                options=options
            )
            logging.info("WebDriver initialized successfully.")
            return driver
        except WebDriverException as e:
            logging.error(f"Error initializing WebDriver: {e}")
            raise

    def search(self, query: str) -> Optional[SearchResult]:
        """
        Perform a search for the given query and retrieve related URLs, images, and videos.

        Args:
            query (str): The search query.

        Returns:
            Optional[SearchResult]: The search results containing URLs, images, and videos.
        """
        result = SearchResult(query=query)
        try:
            # General Web Search
            general_search_url = f"https://www.google.com/search?q={query.replace(' ', '+')}"
            self.driver.get(general_search_url)
            logging.info(f"Navigated to {general_search_url}")

            # Wait until the general search results are loaded
            WebDriverWait(self.driver, self.wait_time).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "div.yuRUbf > a"))
            )

            # Parse page source with BeautifulSoup
            soup = BeautifulSoup(self.driver.page_source, "html.parser")

            # Extract general URLs
            links = soup.select("div.yuRUbf > a")
            for link in links:
                href = link.get("href")
                if href:
                    result.urls.append(href)
            logging.info(f"Found {len(result.urls)} general URLs.")

            # Image Search
            image_search_url = f"https://www.google.com/search?q={query.replace(' ', '+')}&tbm=isch"
            self.driver.get(image_search_url)
            logging.info(f"Navigated to {image_search_url}")

            # Wait until the images are loaded
            WebDriverWait(self.driver, self.wait_time).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "img"))
            )

            # Parse page source with BeautifulSoup
            soup = BeautifulSoup(self.driver.page_source, "html.parser")

            # Extract image URLs
            images = soup.find_all("img")
            for img in images:
                src = img.get("src")
                if src and src.startswith("http"):
                    result.image_urls.append(src)
            logging.info(f"Found {len(result.image_urls)} images.")

            # Video Search
            video_search_url = f"https://www.google.com/search?q={query.replace(' ', '+')}&tbm=vid"
            self.driver.get(video_search_url)
            logging.info(f"Navigated to {video_search_url}")

            # Wait until the video results are loaded
            WebDriverWait(self.driver, self.wait_time).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "a[href*='/url?q=']"))
            )

            soup = BeautifulSoup(self.driver.page_source, "html.parser")

            # Extract video URLs
            videos = soup.find_all("a", href=True)
            for a in videos:
                href = a.get("href")
                if "url?q=" in href:
                    clean_url = href.split("url?q=")[1].split("&")[0]
                    result.video_urls.append(clean_url)
            logging.info(f"Found {len(result.video_urls)} videos.")

            return result

        except TimeoutException as e:
            logging.error(f"Timeout occurred: {e}")
        except NoSuchElementException as e:
            logging.error(f"Element not found: {e}")
        except Exception as e:
            logging.error(f"An unexpected error occurred: {e}")
        finally:
            self.driver.quit()
            logging.info("WebDriver closed.")

        return None

    def upload_file(self, upload_url: str, file_path: str) -> bool:
        """
        Upload a file to the specified URL.

        Args:
            upload_url (str): The URL of the upload page.
            file_path (str): The path to the file to upload.

        Returns:
            bool: True if upload was successful, False otherwise.
        """
        try:
            self.driver.get(upload_url)
            logging.info(f"Navigated to {upload_url}")

            # Wait until the file input is present
            WebDriverWait(self.driver, self.wait_time).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, "input[type='file']"))
            )

            # Set file detector for remote if necessary
            if hasattr(self.driver, 'file_detector'):
                self.driver.file_detector = LocalFileDetector()

            # Find the file input and upload the file
            file_input = self.driver.find_element(By.CSS_SELECTOR, "input[type='file']")
            file_input.send_keys(os.path.abspath(file_path))
            logging.info(f"Uploaded file: {file_path}")

            # Submit the form
            submit_button = self.driver.find_element(By.ID, "file-submit")
            submit_button.click()
            logging.info("Submitted the upload form.")

            # Wait for the upload to complete
            WebDriverWait(self.driver, self.wait_time).until(
                EC.presence_of_element_located((By.ID, "uploaded-files"))
            )

            uploaded_file = self.driver.find_element(By.ID, "uploaded-files").text
            if os.path.basename(file_path) == uploaded_file:
                logging.info("File uploaded successfully.")
                return True
            else:
                logging.error("Uploaded file name does not match.")
                return False

        except Exception as e:
            logging.error(f"Error during file upload: {e}")
            return False

    def download_file(self, download_url: str, file_name: str, timeout: int = 30) -> bool:
        """
        Download a file from the specified URL.

        Args:
            download_url (str): The URL to download the file from.
            file_name (str): The expected name of the downloaded file.
            timeout (int): Maximum time to wait for the download to complete.

        Returns:
            bool: True if download was successful, False otherwise.
        """
        try:
            self.driver.get(download_url)
            logging.info(f"Navigated to {download_url}")

            # Initiate the download by clicking the download link/button
            download_element = self.driver.find_element(By.LINK_TEXT, file_name)
            download_element.click()
            logging.info(f"Initiated download for {file_name}")

            # Wait for the file to appear in the download directory
            download_path = os.path.join(self.download_dir, file_name)
            logging.info(f"Waiting for {download_path} to appear...")

            for _ in range(timeout):
                if os.path.exists(download_path):
                    logging.info(f"Download completed: {download_path}")
                    return True
                time.sleep(1)

            logging.error(f"Download timed out after {timeout} seconds.")
            return False

        except Exception as e:
            logging.error(f"Error during file download: {e}")
            return False

    def close(self) -> None:
        """Close the WebDriver."""
        if self.driver:
            self.driver.quit()
            logging.info("WebDriver closed.")


def main() -> None:
    """Main function to execute the search tool."""
    query = "OpenAI ChatGPT"

    search_tool = AdvancedSearchTool(headless=False)  # Headless=False for debugging
    result = search_tool.search(query=query)

    if result:
        logging.info(f"Search Results for '{result.query}':")

        logging.info(f"General URLs ({len(result.urls)}):")
        for url in result.urls[:5]:  # Display first 5 URLs
            logging.info(f" - {url}")

        logging.info(f"Image URLs ({len(result.image_urls)}):")
        for img_url in result.image_urls[:5]:  # Display first 5 Image URLs
            logging.info(f" - {img_url}")

        logging.info(f"Video URLs ({len(result.video_urls)}):")
        for vid_url in result.video_urls[:5]:  # Display first 5 Video URLs
            logging.info(f" - {vid_url}")
    else:
        logging.error("Failed to retrieve search results.")

    # Example usage of upload and download functionalities
    # Uncomment and modify the following lines as needed

    # Upload Example
    # upload_success = search_tool.upload_file(
    #     upload_url="https://the-internet.herokuapp.com/upload",
    #     file_path="path/to/your/file.png"
    # )
    # logging.info(f"Upload successful: {upload_success}")

    # Download Example
    # download_success = search_tool.download_file(
    #     download_url="https://www.selenium.dev/selenium/web/downloads/download.html",
    #     file_name="file_1.txt"
    # )
    # logging.info(f"Download successful: {download_success}")

    search_tool.close()


if __name__ == "__main__":
    main()