Selenium Python Vejledning med WebDriver (eksempel)

⚡ Smart opsummering

Selenium med Python pairs the WebDriver automation library with Python concise syntax to test web applications across Firefox, Chrome, and Internet Explorer. This walkthrough configures PyDev in Eclipse, writes login scripts, and explains why teams prefer Python i løbet af Java.

  • 🐍 Python Fordel: Less verbose syntax makes Selenium scripts easier to read and maintain.
  • 🌐 WebDriver: Sends standard commands to Firefox, Chrome, and IE regardless of browser design.
  • 🧩 PyDev Opsætning: Installer PyDev plugin i Eclipse og indstil Python tolk.
  • 📝 Login Scripts: Locate fields by ID, send keys, and submit the form automatically.
  • Title Assertion: WebDriverWait plus assert verifies the page title after login.
  • 🤖 AI Assist: AI tools generate locators and Selenium Python scripts from plain prompts.

Selenium Python Tutorial with WebDriver

Selenium med Python

Selenium understøtninger Python og dermed kan bruges som Selenium WebDriver med Python til testning.

  • Python is easy compared to other programming languages, having far less verbose syntax.
  • Python API'er giver dig mulighed for at oprette forbindelse til browseren gennem Selenium.
  • Selenium sender standarden Python commands to different browsers, despite variation in their browser design.

Du kan køre Selenium med Python scripts til Firefox, Chrome, IE, etc. on different operating systems.

Hvad er Python?

Python er et objektorienteret scriptsprog på højt niveau. Den er designet på en brugervenlig måde. Python uses simple English keywords, which are easy to interpret. It has fewer syntax complications than any other programmeringssprog.

Se nogle af eksemplerne i tabellen nedenfor.

Søgeord Betydning Brug
Elif Ellers hvis Ellers hvis
andet Else hvis: X; elif: Y; andet: J
undtagen Do this, if an exception happens undtagen ValueError, a: udskriv en
exec Kør streng som Python exec 'print "hej verden!"'

Hvad er Selenium?

Selenium is a tool to test your web application. You can do this in various ways, for instance:

  • Permit it to tap on buttons.
  • Enter content in forms.
  • Skim dit websted for at kontrollere, om alt er "OK" og så videre.

Sådan installeres og konfigureres PyDev in Eclipse

PyDev er Python udviklingsmiljø for Eclipse.

Trin 1) Gå til Eclipse Marketplace. Help > Install New Software.

Installer og konfigurer PyDev in Eclipse

The next step is to install the “pydev IDE” for Eclipse.

Trin 2) I dette trin:

  1. Search for “http://pydev.org/updates” in Work with, and then
  2. Select all listed items and click on Next twice.
  3. Accept the License Agreement and click Finish.

Installer og konfigurer PyDev in Eclipse

Trin 3) You may encounter a Security Warning. Click on “Install Anyway”.

Installer og konfigurer PyDev in Eclipse

Trin 4) Set preferences so you can use Python as per the project need. Go to Window > Preferences > PyDev > Tolk > Python Tolk.

Installer og konfigurer PyDev in Eclipse

Indstil standard Python Interpreter, just as you set the Java compiler for running Java code. To change the interpreter name, click the Browse for python/pypy exe button.

Installer og konfigurer PyDev in Eclipse

Trin 5) I dette trin skal du angive "tolkenavnet" og "exe"-filstien til Python.

  1. Klik på 'Gennemse' og find python.exe, hvor du installerede Python.
  2. Klik på knappen 'OK'.
  3. Select all the folders and click on OK.
  4. Klik på "Anvend og luk".

Installer og konfigurer PyDev in Eclipse

Trin 6) Make a new project in Python. In this step:

  1. Højreklik PyDev Pakke Explorer > Ny.
  2. Vælg mulighed andre.

Installer og konfigurer PyDev in Eclipse

  1. Vælg "PyDev > PyDev Projekt".
  2. Press the ‘Next’ button.

Installer og konfigurer PyDev in Eclipse

  1. Name your project.
  2. Klik på "Afslut".

Installer og konfigurer PyDev in Eclipse

Du kan se det nye Python (PyDev) projektet er oprettet.

Trin 7) After creating the ‘PyDev Project', vil du oprette en ny Python pakke.

  1. Højreklik på Projekt > Ny > PyDev Pakke.
  2. Name your package and click Finish.

Installer og konfigurer PyDev in Eclipse

Installer og konfigurer PyDev in Eclipse

Trin 8) If you see in the below screenshot, a new package is created.

Installer og konfigurer PyDev in Eclipse

Opret derefter en PyDev module. The module contains Python files for initialization, whose functions can be imported into another module, avoiding re-writing the program.

Trin 9) Opret en ny PyDev modul. Højreklik på pakke > Ny > PyDev modul.

Installer og konfigurer PyDev in Eclipse

Name your module and click “Finish”.

Installer og konfigurer PyDev in Eclipse

Select Empty Template and click “OK”.

Installer og konfigurer PyDev in Eclipse

Trin 10) Skriv din kode til Selenium med Python som vist nedenfor.

Installer og konfigurer PyDev in Eclipse

Sådan opretter du testscripts i Selenium med Python

I denne Selenium WebDriver med Python example, we did automation for the “Facebook login page” using the Firefox chauffør.

Selenium med Python Eksempel 1: Log ind på Facebook

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
user_name = "YOUR EMAILID"
password = "YOUR PASSWORD"
driver = webdriver.Firefox()
driver.get("https://www.facebook.com")
element = driver.find_element_by_id("email")
element.send_keys(user_name)
element = driver.find_element_by_id("pass")
element.send_keys(password)
element.send_keys(Keys.RETURN)
element.close()

Øjebliksbillede af Code

Opret testscripts i Selenium med Python

Forklaring af koden

  • Code linje 1: From the selenium module, import webdriver.
  • Code linje 2: From the selenium module, import Keys.
  • Code linje 3: user_name is a variable used to store the value of the username.
  • Code linje 4: The variable “password” will be used to store the value of the password.
  • Code linje 5: Initialize “Firefox” ved at lave et objekt af det.
  • Code linje 6: The “driver.get” method navigates to the page given by the URL. WebDriver waits until the page has fully loaded before returning control to your script.
  • Code linje 7: Find the textbox element where the “email” has to be written.
  • Code linje 8: Send the values to the email section.
  • Code linje 9: Same for the password.
  • Code linje 10: Send values to the password section.
  • Code linje 11: element.send_keys(Keys.RETURN) presses enter after the values are inserted.
  • Code linje 12: Luk.

Output: The values of the username “guru99” and password are entered.

Opret testscripts i Selenium med Python

The Facebook page will log in with the email and password. Page opened (see image below).

Opret testscripts i Selenium med Python

Selenium med Python Example 2: Login into Facebook & Check Title

In this example, we will open a login page, fill in the required fields “username” and “password”, and check the page title.

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
# Step 1) Open Firefox
browser = webdriver.Firefox()
# Step 2) Navigate to Facebook
browser.get("http://www.facebook.com")
# Step 3) Search & Enter the Email or Phone field & Enter Password
username = browser.find_element_by_id("email")
password = browser.find_element_by_id("pass")
submit   = browser.find_element_by_id("loginbutton")
username.send_keys("YOUR EMAILID")
password.send_keys("YOUR PASSWORD")
# Step 4) Click Login
submit.click()
wait = WebDriverWait( browser, 5 )
page_title = browser.title
assert page_title == "Facebook"

Snapshot af koden

Opret testscripts i Selenium med Python

Forklaring af koden:

  • Code linje 1-2: Import selenium packages.
  • Code linje 4: Initialiser Firefox by creating an object.
  • Code linje 6: Get the login page (Facebook).
  • Code linje 8-10: Fetch username, password input boxes and the submit button.
  • Code linje 11-12: Enter data into the username and password input boxes.
  • Code linje 14: Klik på knappen "Send".
  • Code linje 15: Create a wait object with a timeout of 5 seconds.
  • Code linje 16: Capture the title from the “browser” object.
  • Code linje 17: Test the captured title string with “Facebook”.

Hvorfor vælge Python i løbet af Java in Selenium

A few points that favor Python i løbet af Java at bruge med Selenium er:

  1. Java programmer har en tendens til at køre langsommere i forhold til Python programmer.
  2. Java uses traditional braces to start and end blocks, while Python bruger indrykning.
  3. Java anvender statisk typing, mens Python er dynamisk indtastet.
  4. Python er enklere og mere kompakt i forhold til Java.

Ofte Stillede Spørgsmål

Run pip install selenium. Modern Selenium skibe med Selenium Manager, which downloads the matching browser driver automatically, so no manual chromedriver setup is needed.

WebDriver is the Selenium interface that drives a real browser, sending commands to Firefox, Chrome, or Edge to control navigation, clicks, and form input.

Selenium 4 removed find_element_by_id. Use the By class: from selenium.webdriver.common.by import By, then driver.find_element(By.ID, “email”).

Implicit wait polls the DOM for a set time. Explicit wait (WebDriverWait) pauses until a specific condition is met. Avoid mixing them to prevent unpredictable timing.

Nej. PyDev in Eclipse is one option. You can also run Selenium Python scripts in PyCharm, VS Code, or from the command line.

Selenium WebDriver supports Firefox, Chrome, Edge, Safari, and Internet Explorer. The same Python script runs across them by swapping føreren.

Yes. AI assistants like ChatGPT turn a plain-language test description into Selenium Python code, suggest locators, and convert old find_element_by_id calls to By syntax.

Yes. GitHub Copilot suggests stable locators, explains NoSuchElementException errors, and recommends explicit waits, reducing flaky tests on dynamic pages.

Opsummer dette indlæg med: