0Pricing
Web Scraping & Bots · Lekcja

Wprowadzenie do Selenium

Rozpoczną Państwo pracę z Selenium, zaawansowanym narzędziem do automatyzacji przeglądarki i scrapowania treści renderowanych przez JavaScript.

Wprowadzenie do Selenium to bezpłatna lekcja Web Scraping & Bots na CoddyKit. To lekcja 1 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Web Scraping & Bots, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Web Scraping & Bots zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

Dynamic Content Challenge

Most websites today aren't static pages. They use JavaScript to load content after the initial page renders.

Think of social media feeds, search results that update as you scroll, or interactive forms. Traditional scraping tools (like Requests) often miss this content because they only fetch the initial HTML.

Meet Selenium WebDriver

Selenium WebDriver is a powerful tool designed to automate web browsers. Unlike libraries that just fetch HTML, Selenium actually launches a real browser (like Chrome or Firefox).

This means it can execute JavaScript, interact with elements, and see the web page exactly as a human user would, making it perfect for dynamic content.

Selenium's Core Idea

Selenium works by sending commands to a specific browser driver (e.g., ChromeDriver for Chrome, GeckoDriver for Firefox).

  • Your Python script tells the driver what actions to perform.
  • The driver then controls the actual browser.
  • The browser executes these actions (navigating, clicking, typing) and returns the updated page state or data.

Install Selenium Library

First, let's install the Selenium library for Python. You can do this using pip, Python's package installer.

Open your terminal or command prompt and run:

pip install selenium

This command downloads and installs the necessary Python components to interact with browsers.

Get Your Browser Driver

Selenium needs a specific browser driver to control your browser. For Chrome, you'll need ChromeDriver. For Firefox, it's GeckoDriver.

1. Check your browser version (e.g., Chrome -> Help -> About Google Chrome).

2. Download the matching driver from its official site:

Place the downloaded driver executable (e.g., chromedriver.exe) in a location accessible by your system's PATH, or note its full path.

Launch Your First Browser

Let's write our first script to open a Chrome browser window using Selenium WebDriver.

Make sure your chromedriver is accessible (either in your PATH or specify its path directly in the Service object).

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time

def main():
    driver = None
    try:
        # IMPORTANT: Ensure ChromeDriver is installed and in your system PATH.
        # If not, specify its path directly:
        # service = Service("/path/to/your/chromedriver") 
        # driver = webdriver.Chrome(service=service)
        
        driver = webdriver.Chrome() # Assumes chromedriver is in PATH
        print("Chrome browser launched successfully!")
        
        time.sleep(5) # Keep browser open for 5 seconds to observe
        
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        if driver:
            driver.quit() # Always close the browser
            print("Browser closed.")

if __name__ == "__main__":
    main()

Go to a Web Page

Once the browser is open, you can tell it to navigate to any URL using the .get() method.

This is like typing a URL into the address bar and pressing Enter. The browser will load the page, including any JavaScript content.

from selenium import webdriver
import time

def main():
    driver = None
    try:
        driver = webdriver.Chrome() 
        print("Browser launched.")
        
        print("Navigating to example.com...")
        driver.get("https://www.example.com") 
        
        print(f"Current page title: {driver.title}")
        print(f"Current URL: {driver.current_url}")
        
        time.sleep(5) # Keep browser open to see the page
        
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        if driver:
            driver.quit()
            print("Browser closed.")

if __name__ == "__main__":
    main()

Waiting for Content

Web pages often take time to load completely, especially with dynamic content. Selenium provides ways to wait for elements to appear.

For now, we'll use a simple time.sleep() to pause execution. Later lessons will cover more robust explicit and implicit waits, which are more efficient.

  • time.sleep(seconds): Pauses execution for a fixed duration.

Always Close Your Browser

It's crucial to close the browser window when your script is done. This frees up system resources and prevents lingering browser processes.

Use the .quit() method on your WebDriver instance. This closes the browser and ends the WebDriver session cleanly.

from selenium import webdriver
import time

def main():
    driver = None
    try:
        driver = webdriver.Chrome() 
        print("Browser launched.")
        
        driver.get("https://www.example.com") 
        print(f"Navigated to: {driver.current_url}")
        
        time.sleep(3) # Wait a bit to see the page
        
    except Exception as e:
        print(f"An error occurred: {e}")
    finally:
        if driver:
            driver.quit() # This line closes the browser window
            print("Browser closed successfully!")

if __name__ == "__main__":
    main()

Quick Check

You've launched your first browser with Selenium! What is the primary purpose of using Selenium WebDriver compared to libraries like Requests for web scraping?

Recap & Next Steps

In this lesson, you learned:

  • Why Selenium is essential for handling dynamic web content.
  • How to install the Selenium library and obtain a browser driver.
  • To launch a browser, navigate to a URL, and close the session cleanly.

Next, we'll dive deeper into automating browser interactions like clicks, form submissions, and finding specific elements on a page!

Często zadawane pytania

Czy lekcja „Wprowadzenie do Selenium” jest bezpłatna?

Tak — pełny tekst „Wprowadzenie do Selenium” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Web Scraping & Bots, przejdź na CoddyKit PRO. Kurs Web Scraping & Bots zawiera 4 lekcji w sumie.

Co nauczysz się w „Wprowadzenie do Selenium”?

Rozpoczną Państwo pracę z Selenium, zaawansowanym narzędziem do automatyzacji przeglądarki i scrapowania treści renderowanych przez JavaScript. Ćwiczysz Web Scraping & Bots z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Web Scraping & Bots?

Nie wymagamy żadnego doświadczenia. Web Scraping & Bots w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 1 z 4.

Ile czasu zajmuje lekcja „Wprowadzenie do Selenium”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Web Scraping & Bots?

Tak. Każda lekcja Web Scraping & Bots zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Wprowadzenie do Selenium
  2. Automatyzacja interakcji z przeglądarką
  3. Ekstrakcja danych z JavaScriptu
  4. Strategie oczekiwania dla stron dynamicznych
← Powrót do Web Scraping & Bots