Pengenalan
Selenium WebDriver telah menjadi standar industri untuk automated browser testing. Dengan Selenium, Anda dapat mengotomatisasi interaksi pengguna dengan web browser, memungkinkan pengujian yang lebih cepat, lebih reliable, dan lebih scalable dibanding manual testing.
Apa itu Selenium
Definisi Selenium
Selenium adalah suite of tools yang digunakan untuk automated browser testing. Selenium adalah open-source project yang mendukung berbagai browser dan platform.
Sejarah Singkat:
1
2
3
4
5
6
7
| 2004: Jason Huggins membuat Selenium di ThoughtWorks
2005: Selenium dirilis sebagai open-source project
2006: Selenium Remote Control (RC) diluncurkan
2011: Selenium WebDriver menjadi standar industri
2016: Selenium 3 dirilis
2021: Selenium 4 dengan fitur-fitur modern
2024: Selenium terus berkembang dengan community support
|
Komponen Selenium Suite
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
| SELENIUM SUITE
═════════════════════════════════════════════════════════════
1. SELENIUM IDE
├─ Browser extension
├─ Record & playback
├─ No coding required
└─ Good for simple tests
2. SELENIUM REMOTE CONTROL (RC) - DEPRECATED
├─ JavaScript-based
├─ Injected into browser
├─ Slower
└─ Legacy tool (not recommended)
3. SELENIUM WEBDRIVER ⭐ MAIN TOOL
├─ Native browser automation
├─ Direct communication with browser
├─ Multiple language support
├─ Fast & reliable
└─ Industry standard
4. SELENIUM GRID
├─ Run tests in parallel
├─ Distribute across machines
├─ Cross-browser testing
└─ Scalable infrastructure
|
Apa itu Selenium WebDriver
Selenium WebDriver adalah tool yang memungkinkan Anda untuk menulis automated tests yang berinteraksi dengan web applications. WebDriver menyediakan simple API untuk mengontrol browser dan berinteraksi dengan HTML elements.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| SELENIUM WEBDRIVER ARCHITECTURE
═════════════════════════════════════════════════════════════
Your Test Script
│
├─ Python binding (selenium.webdriver)
│
├─ WebDriver API (JSON Wire Protocol / W3C WebDriver)
│
├─ Driver (ChromeDriver, GeckoDriver, EdgeDriver)
│
└─ Browser (Chrome, Firefox, Edge, Safari)
Flow:
1. Your code → selenium.webdriver.Chrome()
2. Creates ChromeDriver process
3. ChromeDriver communicates with Chrome browser
4. Browser performs actions (click, type, navigate)
5. Results returned to your test
|
Supported Browsers
Browser Support Matrix:
| Browser | Driver | Status | Support |
|---|
| Chrome | chromedriver | ✓ Full | Windows,Mac, Linux |
| Firefox | geckodriver | ✓ Full | Windows,Mac, Linux |
| Edge | msedgedriver | ✓ Full | Windows,Mac, Linux |
| Safari | safaridriver | ✓ Full | macOS only |
| IE | iedriver | ⚠ Legacy | Not recom. |
Key Features
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| ✅ SELENIUM WEBDRIVER FEATURES:
1. Multi-Language Support
├─ Python
├─ Java
├─ C#
├─ JavaScript/Node.js
├─ Ruby
└─ Kotlin
2. Multi-Browser Support
├─ Chrome/Chromium
├─ Firefox
├─ Edge
├─ Safari
└─ Others (via Selenium Grid)
3. Cross-Platform
├─ Windows
├─ macOS
├─ Linux
└─ Mobile (via Appium)
4. Powerful API
├─ Find elements
├─ Click, type, submit
├─ Navigate
├─ Wait for conditions
├─ Execute JavaScript
└─ Take screenshots
5. Integration
├─ Unit test frameworks
├─ CI/CD pipelines
├─ Test management tools
└─ Cloud services
|
Kenapa Harus Selenium
Keunggulan Selenium
1. 🆓 Open Source & Free
1
2
3
4
5
6
7
8
9
10
11
12
13
| SELENIUM adalah open-source:
✓ Gratis selamanya
✓ Transparansi kode
✓ Community-driven development
✓ No vendor lock-in
Dibanding tool komersial:
❌ UFT/QTP: $5000+ per lisensi
❌ Ranorex: $3000+ per tahun
❌ TestComplete: $2000+ per tahun
SELENIUM: $0 ✓
|
1
2
3
4
5
6
7
8
| SELENIUM bekerja dengan:
✓ Semua major browsers (Chrome, Firefox, Edge, Safari)
✓ Semua OS (Windows, macOS, Linux)
✓ Mobile browsers (via Appium)
✓ Headless mode (faster)
Dibanding tools lain yang limited ke satu platform/browser
|
3. 💻 Multiple Programming Languages
1
2
3
4
5
6
7
8
9
| Pilih bahasa yang Anda suka:
✓ Python (most popular for QA)
✓ Java (traditional)
✓ C# (for .NET)
✓ JavaScript (for web developers)
✓ Ruby, Kotlin, dan lainnya
Fleksibilitas untuk setiap tim
|
4. 🤖 Easy to Learn & Use
1
2
3
4
5
6
7
8
9
10
11
12
13
| Selenium API sederhana & intuitif:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("https://example.com")
element = driver.find_element("id", "submit")
element.click()
driver.quit()
Dibanding tool proprietary dengan learning curve tinggi
|
1
2
3
4
5
6
7
8
9
10
11
| SELENIUM punya:
✓ Dokumentasi lengkap
✓ Ribuan tutorials
✓ Stack Overflow Q&A
✓ Community forums
✓ GitHub discussions
✓ Conference talks
✓ Books & courses
Mudah menemukan help & solutions
|
6. 🔧 Extensive Integration Support
1
2
3
4
5
6
7
8
9
10
| Selenium terintegrasi dengan:
✓ Test frameworks (unittest, pytest, TestNG)
✓ CI/CD tools (Jenkins, GitHub Actions, GitLab CI)
✓ BDD tools (Cucumber, Behave)
✓ Cloud services (BrowserStack, Sauce Labs)
✓ Test management (JIRA, TestRail)
✓ APM tools (DataDog, New Relic)
Perfect untuk enterprise setups
|
7. ⚡ Powerful & Flexible
1
2
3
4
5
6
7
8
9
10
11
12
13
| Selenium dapat:
✓ Automate complex user workflows
✓ Handle JavaScript-heavy sites
✓ Execute custom JavaScript
✓ Handle popups & alerts
✓ Switch between windows
✓ Upload files
✓ Take screenshots
✓ Parallel execution
✓ Headless testing
Tidak terbatas pada simple scenarios
|
8. 🏢 Industry Standard
1
2
3
4
5
6
7
8
9
| SELENIUM adalah pilihan #1:
✓ Used by Google, Facebook, Netflix, Amazon
✓ Recommended by W3C (World Wide Web Consortium)
✓ Supported by major tech companies
✓ Jobs & career opportunities
✓ Future-proof investment
Pilihan aman untuk long-term
|
| Aspek | Selenium | Cypress | Playwright | UFT |
|---|
| Cost | Free ✓ | Free | Free | $5000+ |
| Open Source | Yes ✓ | Yes | Yes | No |
| Browsers | All ✓ | Most | All ✓ | All |
| Languages | 6+ ✓ | JS only | JS/TS | VBScript |
| Learning Curve | Easy ✓ | Easy | Medium | Hard |
| Community | Very Large | Large | Growing | Medium |
| Mobile Support | Yes (Appium) | No | Yes | Yes |
| CI/CD Integration | Excellent ✓ | Good | Good | Good |
| Documentation | Excellent ✓ | Good | Good | Medium |
| Job Market | High ✓ | High | Growing | Stable |
| Performance | Good | Better | Better | Good |
| Flakiness | Low ✓ | Lower | Lower | Medium |
VERDICT: Selenium adalah pilihan terbaik untuk flexibility, cost, dan community support
Instalasi Selenium dengan Python
Prerequisites
1
2
3
4
5
6
7
8
9
10
11
12
| Sebelum install Selenium, pastikan:
✓ Python 3.7+ sudah terinstall
✓ pip (Python package manager) tersedia
✓ Internet connection untuk download packages
✓ Administrator access (untuk install)
Cek Python:
python --version
Cek pip:
pip --version
|
Step 1: Create Virtual Environment
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # Recommended: Use virtual environment
# Create directory
mkdir selenium_project
cd selenium_project
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Verify activation (prompt should show (venv))
|
Step 2: Install Selenium Package
1
2
3
4
5
6
7
| # Install Selenium
pip install selenium
# Verify installation
pip list | grep selenium
# Should output: selenium 4.x.x
|
Step 3: Install WebDriver
Selenium WebDriver membutuhkan driver khusus untuk setiap browser.
For Chrome
1
2
3
4
5
6
7
8
| # Option 1: Using webdriver-manager (Recommended)
pip install webdriver-manager
# Option 2: Manual download
# 1. Visit: https://chromedriver.chromium.org/
# 2. Download matching your Chrome version
# 3. Extract & add to PATH
# 4. Or place in project directory
|
For Firefox
1
2
3
4
5
6
7
| # Option 1: Using webdriver-manager
pip install webdriver-manager
# Option 2: Manual download
# 1. Visit: https://github.com/mozilla/geckodriver/releases
# 2. Download matching your OS
# 3. Extract & add to PATH
|
For Edge
1
2
3
4
5
6
7
| # Option 1: Using webdriver-manager
pip install webdriver-manager
# Option 2: Manual download
# 1. Visit: https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
# 2. Download matching your Edge version
# 3. Extract & add to PATH
|
Step 4: Verify Installation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| # verify_installation.py
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
# Setup driver dengan webdriver-manager
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open website
driver.get("https://www.google.com")
# Print title
print(f"Page title: {driver.title}")
# Close browser
driver.quit()
print("✓ Selenium installation verified successfully!")
|
Requirements File
1
2
3
4
5
| # requirements.txt
selenium==4.15.0
webdriver-manager==4.0.1
pytest==7.4.3
pytest-xdist==3.5.0 # untuk parallel execution
|
Complete Setup Script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| # setup.sh (macOS/Linux) atau setup.bat (Windows)
# Create project structure
mkdir selenium_project
cd selenium_project
mkdir tests
mkdir utils
mkdir reports
# Create virtual environment
python -m venv venv
# Activate venv
source venv/bin/activate # macOS/Linux
# venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
echo "✓ Setup complete! Ready to write tests."
|
Open Browser dengan Selenium
Basic Browser Opening
1. Open Chrome Browser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
# Method 1: Using webdriver-manager (Recommended)
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service)
# Open website
driver.get("https://www.google.com")
# Print page title
print(f"Page title: {driver.title}")
# Close browser
driver.quit()
|
2. Open Firefox Browser
1
2
3
4
5
6
7
8
9
10
11
| from selenium import webdriver
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.firefox.service import Service
service = Service(GeckoDriverManager().install())
driver = webdriver.Firefox(service=service)
driver.get("https://www.google.com")
print(f"Page title: {driver.title}")
driver.quit()
|
3. Open Edge Browser
1
2
3
4
5
6
7
8
9
10
11
| from selenium import webdriver
from webdriver_manager.microsoft import EdgeChromiumDriverManager
from selenium.webdriver.edge.service import Service
service = Service(EdgeChromiumDriverManager().install())
driver = webdriver.Edge(service=service)
driver.get("https://www.google.com")
print(f"Page title: {driver.title}")
driver.quit()
|
Browser Options & Configuration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
| from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
# Create Chrome options
options = Options()
# Option 1: Headless mode (tidak buka window)
options.add_argument("--headless")
# Option 2: Start maximized
options.add_argument("--start-maximized")
# Option 3: Disable notifications
options.add_argument("--disable-notifications")
# Option 4: Disable GPU (faster)
options.add_argument("--disable-gpu")
# Option 5: Set window size
options.add_argument("--window-size=1920,1080")
# Option 6: Disable popup blocker
options.add_argument("--disable-popup-blocking")
# Option 7: Allow insecure certificates (for testing)
options.add_argument("--ignore-certificate-errors")
# Option 8: Set user agent
options.add_argument("user-agent=Mozilla/5.0...")
# Option 9: Disable image loading (faster)
prefs = {"profile.managed_default_content_settings.images": 2}
options.add_experimental_option("prefs", prefs)
# Option 10: Incognito mode
options.add_argument("--incognito")
# Create driver dengan options
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=options)
driver.get("https://www.google.com")
print(f"Page title: {driver.title}")
driver.quit()
|
Advanced Configuration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.wait import WebDriverWait
import time
options = Options()
options.add_argument("--headless")
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Chrome(options=options)
# Set implicit wait (global wait untuk semua elements)
driver.implicitly_wait(10) # 10 seconds
# Set page load timeout
driver.set_page_load_timeout(30) # 30 seconds
# Set script timeout
driver.set_script_timeout(30) # 30 seconds
# Open website
driver.get("https://www.example.com")
# Get page information
print(f"Title: {driver.title}")
print(f"URL: {driver.current_url}")
print(f"Source length: {len(driver.page_source)}")
# Window operations
driver.maximize_window()
print(f"Window size: {driver.get_window_size()}")
# Close browser
driver.quit()
|
Interaksi dengan HTML Elements
Finding Elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# Method 1: Find by ID
element = driver.find_element(By.ID, "element_id")
# Method 2: Find by Name
element = driver.find_element(By.NAME, "element_name")
# Method 3: Find by Class Name
element = driver.find_element(By.CLASS_NAME, "class_name")
# Method 4: Find by CSS Selector
element = driver.find_element(By.CSS_SELECTOR, "div.class > button")
# Method 5: Find by XPath
element = driver.find_element(By.XPATH, "//button[@id='submit']")
# Method 6: Find by Link Text
element = driver.find_element(By.LINK_TEXT, "Click Here")
# Method 7: Find by Partial Link Text
element = driver.find_element(By.PARTIAL_LINK_TEXT, "Click")
# Method 8: Find by Tag Name
element = driver.find_element(By.TAG_NAME, "button")
# Method 9: Find Multiple Elements
elements = driver.find_elements(By.CLASS_NAME, "item")
print(f"Found {len(elements)} elements")
# Method 10: Find with WebDriverWait (Recommended)
wait = WebDriverWait(driver, 10)
element = wait.until(
EC.presence_of_element_located((By.ID, "element_id"))
)
|
Locator Strategies Best Practices
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| Best Locators (in order of preference):
1. ✅ ID (Most stable)
└─ find_element(By.ID, "id_value")
2. ✅ Name
└─ find_element(By.NAME, "name_value")
3. ✅ CSS Selector (Flexible)
└─ find_element(By.CSS_SELECTOR, ".class > button")
4. ✅ XPath (Last resort)
└─ find_element(By.XPATH, "//button[@id='submit']")
❌ Avoid:
└─ Class Name (if too generic)
└─ Tag Name (too generic)
└─ Link Text (if link text changes)
└─ Absolute XPath (brittle)
|
Interacting with Elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
| from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# 1. CLICK
button = driver.find_element(By.ID, "submit_button")
button.click()
# 2. TYPE (Clear & Type)
text_input = driver.find_element(By.ID, "search_box")
text_input.clear()
text_input.send_keys("Selenium WebDriver")
# 3. SUBMIT FORM
form = driver.find_element(By.ID, "login_form")
form.submit()
# 4. PRESS KEYS
input_field = driver.find_element(By.ID, "input")
input_field.send_keys(Keys.ENTER)
input_field.send_keys(Keys.TAB)
input_field.send_keys(Keys.ESCAPE)
input_field.send_keys(Keys.BACKSPACE)
input_field.send_keys(Keys.DELETE)
input_field.send_keys(Keys.CONTROL + "a") # Select all
# 5. GET TEXT
element = driver.find_element(By.ID, "message")
text = element.text
print(f"Element text: {text}")
# 6. GET ATTRIBUTE
link = driver.find_element(By.TAG_NAME, "a")
href = link.get_attribute("href")
print(f"Link URL: {href}")
# 7. CHECK IF ELEMENT DISPLAYED
element = driver.find_element(By.ID, "popup")
if element.is_displayed():
print("Element is visible")
# 8. CHECK IF ELEMENT ENABLED
button = driver.find_element(By.ID, "button")
if button.is_enabled():
print("Button is clickable")
# 9. CHECK IF ELEMENT SELECTED
checkbox = driver.find_element(By.ID, "checkbox")
if checkbox.is_selected():
print("Checkbox is checked")
# 10. MOUSE HOVER
element = driver.find_element(By.ID, "hover_element")
ActionChains(driver).move_to_element(element).perform()
# 11. RIGHT CLICK
ActionChains(driver).context_click(element).perform()
# 12. DOUBLE CLICK
ActionChains(driver).double_click(element).perform()
# 13. DRAG & DROP
source = driver.find_element(By.ID, "draggable")
target = driver.find_element(By.ID, "droppable")
ActionChains(driver).drag_and_drop(source, target).perform()
# 14. SCROLL
driver.execute_script("window.scrollBy(0, 500);")
# 15. SCREENSHOT
driver.save_screenshot("screenshot.png")
driver.quit()
|
Waiting for Elements
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
| from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome()
driver.get("https://www.example.com")
# 1. IMPLICIT WAIT (Global)
driver.implicitly_wait(10) # Semua find_element() akan wait 10 detik
element = driver.find_element(By.ID, "element")
# 2. EXPLICIT WAIT (Recommended)
wait = WebDriverWait(driver, 10) # Max 10 seconds
# Wait for element to be visible
element = wait.until(
EC.visibility_of_element_located((By.ID, "element"))
)
# Wait for element to be clickable
element = wait.until(
EC.element_to_be_clickable((By.ID, "button"))
)
# Wait for element presence
element = wait.until(
EC.presence_of_element_located((By.CLASS_NAME, "item"))
)
# Wait for element to disappear
wait.until(
EC.invisibility_of_element_located((By.ID, "loader"))
)
# 3. FLUENT WAIT (Advanced)
from selenium.webdriver.support.ui import FluentWait
wait = FluentWait(driver)
wait.until(lambda x: x.find_element(By.ID, "element").is_displayed())
# 4. EXPLICIT SLEEP (Not Recommended - Use Wait)
time.sleep(2) # Tunggu 2 detik
driver.quit()
|
Studi Kasus: Live Coding Examples
Contoh 1: Google Search Test
File: test_google_search.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
| """
Test Case: Search "Selenium WebDriver" on Google
Purpose: Verify Google search functionality
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import time
class TestGoogleSearch:
def setup_method(self):
"""Setup: Run before each test"""
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service)
self.driver.implicitly_wait(10)
def teardown_method(self):
"""Teardown: Run after each test"""
self.driver.quit()
def test_google_search_selenium(self):
"""Test: Search for 'Selenium WebDriver' on Google"""
# STEP 1: Open Google
print("Opening Google...")
self.driver.get("https://www.google.com")
# STEP 2: Accept cookies if present
try:
cookies_button = WebDriverWait(self.driver, 5).until(
EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'Accept')]"))
)
cookies_button.click()
print("Cookies accepted")
except:
print("No cookies popup")
# STEP 3: Find search box
print("Finding search box...")
search_box = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.NAME, "q"))
)
# STEP 4: Type search query
print("Typing search query...")
search_box.send_keys("Selenium WebDriver")
# STEP 5: Press Enter
print("Pressing Enter...")
search_box.send_keys(Keys.ENTER)
# STEP 6: Wait for results
print("Waiting for search results...")
WebDriverWait(self.driver, 10).until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.g"))
)
# STEP 7: Verify results
print("Verifying results...")
results = self.driver.find_elements(By.CSS_SELECTOR, "div.g")
print(f"Found {len(results)} search results")
assert len(results) > 0, "No search results found"
# STEP 8: Get first result
first_result = results[0]
first_result_text = first_result.text
print(f"First result: {first_result_text[:100]}...")
# STEP 9: Take screenshot
self.driver.save_screenshot("google_search_results.png")
print("Screenshot saved")
print("✓ Test passed!")
# Run test
if __name__ == "__main__":
test = TestGoogleSearch()
test.setup_method()
test.test_google_search_selenium()
test.teardown_method()
|
File: test_form_filling.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
| """
Test Case: Fill and submit a form on a test website
Website: https://practicetestautomation.com/practice-test-login/
Purpose: Verify form interaction capabilities
"""
from selenium import webdriver
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
from selenium.webdriver.chrome.service import Service
class TestFormFilling:
def setup_method(self):
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service)
self.driver.implicitly_wait(10)
def teardown_method(self):
self.driver.quit()
def test_login_form(self):
"""Test: Fill login form with valid credentials"""
# STEP 1: Navigate to login page
print("Step 1: Navigate to login page")
self.driver.get("https://practicetestautomation.com/practice-test-login/")
# STEP 2: Verify page title
print("Step 2: Verify page title")
page_title = self.driver.title
print(f"Page title: {page_title}")
assert "Login" in page_title, "Wrong page loaded"
# STEP 3: Find username field
print("Step 3: Find username field")
username_field = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.ID, "username"))
)
# STEP 4: Enter username
print("Step 4: Enter username")
username_field.clear()
username_field.send_keys("student")
# Verify text was entered
entered_username = username_field.get_attribute("value")
print(f"Username entered: {entered_username}")
assert entered_username == "student", "Username not entered correctly"
# STEP 5: Find password field
print("Step 5: Find password field")
password_field = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.ID, "password"))
)
# STEP 6: Enter password
print("Step 6: Enter password")
password_field.clear()
password_field.send_keys("Password123")
# Verify password field is masked
password_type = password_field.get_attribute("type")
print(f"Password field type: {password_type}")
assert password_type == "password", "Password field not masked"
# STEP 7: Find and click submit button
print("Step 7: Find and click submit button")
submit_button = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.ID, "submit"))
)
# Verify button is enabled
is_enabled = submit_button.is_enabled()
print(f"Submit button enabled: {is_enabled}")
assert is_enabled, "Submit button is not enabled"
# Click submit
submit_button.click()
print("Submit button clicked")
# STEP 8: Verify login success
print("Step 8: Verify login success")
# Wait for success message
try:
success_msg = WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.CLASS_NAME, "post-title"))
)
success_text = success_msg.text
print(f"Success message: {success_text}")
assert "Congratulations" in success_text or "successfully" in success_text.lower()
except:
print("Success message not found - checking URL instead")
current_url = self.driver.current_url
print(f"Current URL: {current_url}")
assert current_url != "https://practicetestautomation.com/practice-test-login/"
# STEP 9: Take screenshot
self.driver.save_screenshot("login_success.png")
print("Screenshot saved")
print("✓ Test passed!")
# Run test
if __name__ == "__main__":
test = TestFormFilling()
test.setup_method()
test.test_login_form()
test.teardown_method()
|
File: test_shopping_cart.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
| """
Test Case: Add items to shopping cart
Website: http://www.ebay.com (or any e-commerce site)
Purpose: Verify shopping cart functionality
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
class TestShoppingCart:
def setup_method(self):
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service)
self.driver.implicitly_wait(10)
def teardown_method(self):
self.driver.quit()
def test_add_items_to_cart(self):
"""Test: Search for items and add to cart"""
print("Step 1: Open shopping website")
# Using a practice e-commerce site
self.driver.get("https://www.saucedemo.com")
print("Step 2: Verify page loaded")
page_title = self.driver.title
print(f"Page title: {page_title}")
# If login required, login first
try:
username = self.driver.find_element(By.ID, "user-name")
password = self.driver.find_element(By.ID, "password")
print("Step 3: Login to website")
username.send_keys("standard_user")
password.send_keys("secret_sauce")
login_button = self.driver.find_element(By.ID, "login-button")
login_button.click()
# Wait for products page to load
WebDriverWait(self.driver, 10).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, "inventory_item"))
)
print("Login successful")
except:
print("No login required")
print("Step 4: Find products")
products = self.driver.find_elements(By.CLASS_NAME, "inventory_item")
print(f"Found {len(products)} products")
# Add first product to cart
print("Step 5: Add first product to cart")
if len(products) > 0:
# Find add to cart button in first product
first_product = products[0]
product_name = first_product.find_element(By.CLASS_NAME, "inventory_item_name")
print(f"Adding: {product_name.text}")
add_to_cart_btn = first_product.find_element(By.TAG_NAME, "button")
add_to_cart_btn.click()
print("Added to cart")
# Add second product to cart
print("Step 6: Add second product to cart")
if len(products) > 1:
second_product = products[1]
product_name = second_product.find_element(By.CLASS_NAME, "inventory_item_name")
print(f"Adding: {product_name.text}")
add_to_cart_btn = second_product.find_element(By.TAG_NAME, "button")
add_to_cart_btn.click()
print("Added to cart")
print("Step 7: Verify cart count")
try:
cart_badge = self.driver.find_element(By.CLASS_NAME, "shopping_cart_badge")
cart_count = cart_badge.text
print(f"Items in cart: {cart_count}")
assert int(cart_count) >= 2, "Items not added to cart"
except:
print("Could not find cart badge")
print("Step 8: Click on shopping cart")
cart_icon = self.driver.find_element(By.CLASS_NAME, "shopping_cart_link")
cart_icon.click()
print("Step 9: Verify items in cart")
WebDriverWait(self.driver, 10).until(
EC.presence_of_all_elements_located((By.CLASS_NAME, "cart_item"))
)
cart_items = self.driver.find_elements(By.CLASS_NAME, "cart_item")
print(f"Items in cart view: {len(cart_items)}")
assert len(cart_items) >= 2, "Items not found in cart"
print("Step 10: Take screenshot")
self.driver.save_screenshot("shopping_cart.png")
print("✓ Test passed!")
# Run test
if __name__ == "__main__":
test = TestShoppingCart()
test.setup_method()
test.test_add_items_to_cart()
test.teardown_method()
|
Contoh 4: Advanced Interactions & Windows Handling
File: test_advanced_interactions.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
| """
Test Case: Advanced Selenium interactions
Purpose: Demonstrate multiple browser interactions
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import Select
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service
import time
class TestAdvancedInteractions:
def setup_method(self):
service = Service(ChromeDriverManager().install())
self.driver = webdriver.Chrome(service=service)
self.driver.implicitly_wait(10)
def teardown_method(self):
self.driver.quit()
def test_advanced_interactions(self):
"""Test: Various advanced Selenium interactions"""
print("=" * 50)
print("TEST: Advanced Selenium Interactions")
print("=" * 50)
# Open demo page
print("\n1. NAVIGATE TO WEBSITE")
self.driver.get("https://www.w3schools.com/html/html_forms.asp")
print(f"✓ Title: {self.driver.title}")
# 2. SCROLL
print("\n2. SCROLL PAGE")
self.driver.execute_script("window.scrollBy(0, 500);")
print("✓ Scrolled down 500px")
# 3. KEYBOARD INTERACTIONS
print("\n3. KEYBOARD INTERACTIONS")
body = self.driver.find_element(By.TAG_NAME, "body")
body.send_keys(Keys.HOME) # Go to top
print("✓ Pressed HOME key")
# 4. GET PAGE INFO
print("\n4. GET PAGE INFORMATION")
page_title = self.driver.title
current_url = self.driver.current_url
page_source_length = len(self.driver.page_source)
print(f"✓ Title: {page_title}")
print(f"✓ URL: {current_url}")
print(f"✓ Page source length: {page_source_length} characters")
# 5. WINDOW SIZE
print("\n5. WINDOW MANAGEMENT")
self.driver.maximize_window()
print("✓ Window maximized")
window_size = self.driver.get_window_size()
print(f"✓ Window size: {window_size}")
# 6. OPEN NEW TAB
print("\n6. OPEN NEW TAB")
self.driver.execute_script("window.open('https://www.google.com');")
time.sleep(2)
# Get all windows
all_windows = self.driver.window_handles
print(f"✓ Total windows: {len(all_windows)}")
# Switch to new tab
self.driver.switch_to.window(all_windows[-1])
print(f"✓ Switched to new tab: {self.driver.title}")
# Switch back to original tab
self.driver.switch_to.window(all_windows[0])
print(f"✓ Switched back to: {self.driver.title}")
# 7. HANDLE ALERTS
print("\n7. HANDLE ALERTS")
try:
# Try to find and click button that shows alert
alert_buttons = self.driver.find_elements(By.TAG_NAME, "button")
if alert_buttons:
print(f"✓ Found {len(alert_buttons)} buttons")
except:
print("No alert buttons found")
# 8. DROPDOWN SELECT
print("\n8. DROPDOWN SELECT")
try:
selects = self.driver.find_elements(By.TAG_NAME, "select")
if selects:
select_elem = selects[0]
select = Select(select_elem)
# Select by index
select.select_by_index(1)
print("✓ Selected by index")
# Get selected option
selected = select.first_selected_option
print(f"✓ Selected option: {selected.text}")
except:
print("No select elements found")
# 9. CHECKBOX & RADIO
print("\n9. CHECKBOX & RADIO BUTTONS")
try:
checkboxes = self.driver.find_elements(By.CSS_SELECTOR, "input[type='checkbox']")
if checkboxes:
print(f"✓ Found {len(checkboxes)} checkboxes")
# Check first checkbox
if not checkboxes[0].is_selected():
checkboxes[0].click()
print("✓ Checked checkbox")
except:
print("No checkboxes found")
# 10. EXECUTE JAVASCRIPT
print("\n10. EXECUTE JAVASCRIPT")
result = self.driver.execute_script("return 2 + 2;")
print(f"✓ JavaScript result: {result}")
# Set background color
self.driver.execute_script(
"document.body.style.backgroundColor = 'yellow';"
)
print("✓ Changed background color")
# 11. SCREENSHOT
print("\n11. TAKE SCREENSHOT")
self.driver.save_screenshot("advanced_interactions.png")
print("✓ Screenshot saved")
# 12. COOKIES
print("\n12. COOKIES MANAGEMENT")
self.driver.add_cookie({'name': 'test_cookie', 'value': 'test_value'})
print("✓ Cookie added")
cookies = self.driver.get_cookies()
print(f"✓ Total cookies: {len(cookies)}")
# 13. NAVIGATE ACTIONS
print("\n13. BROWSER NAVIGATION")
self.driver.back()
print("✓ Pressed back button")
self.driver.forward()
print("✓ Pressed forward button")
self.driver.refresh()
print("✓ Refreshed page")
print("\n" + "=" * 50)
print("✓ ALL TESTS PASSED!")
print("=" * 50)
# Run test
if __name__ == "__main__":
test = TestAdvancedInteractions()
test.setup_method()
test.test_advanced_interactions()
test.teardown_method()
|
Best Practices
Selenium Best Practices
1. Use Page Object Model (POM)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| # ❌ BAD: Test scattered across code
def test_login():
driver.find_element(By.ID, "username").send_keys("user")
driver.find_element(By.ID, "password").send_keys("pass")
driver.find_element(By.ID, "submit").click()
assert "Success" in driver.find_element(By.CLASS_NAME, "message").text
# ✅ GOOD: Using Page Object Model
class LoginPage:
def __init__(self, driver):
self.driver = driver
self.username_field = (By.ID, "username")
self.password_field = (By.ID, "password")
self.submit_button = (By.ID, "submit")
self.message = (By.CLASS_NAME, "message")
def login(self, username, password):
self.driver.find_element(*self.username_field).send_keys(username)
self.driver.find_element(*self.password_field).send_keys(password)
self.driver.find_element(*self.submit_button).click()
def get_message(self):
return self.driver.find_element(*self.message).text
# Test using POM
def test_login():
page = LoginPage(driver)
page.login("user", "pass")
assert "Success" in page.get_message()
|
2. Always Use Explicit Waits
1
2
3
4
5
6
7
8
9
| # ❌ BAD: Hard sleep
time.sleep(5)
element = driver.find_element(By.ID, "element")
# ✅ GOOD: Explicit wait
wait = WebDriverWait(driver, 10)
element = wait.until(
EC.presence_of_element_located((By.ID, "element"))
)
|
3. Handle Exceptions Properly
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # ❌ BAD: No exception handling
element = driver.find_element(By.ID, "element")
element.click()
# ✅ GOOD: Exception handling
try:
wait = WebDriverWait(driver, 10)
element = wait.until(
EC.element_to_be_clickable((By.ID, "element"))
)
element.click()
except TimeoutException:
print("Element not found within timeout")
except NoSuchElementException:
print("Element does not exist")
except ElementNotInteractableException:
print("Element cannot be clicked")
|
4. Clean Browser Resources
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| # ✅ GOOD: Always close browser
try:
driver.get("https://example.com")
# Test code
finally:
driver.quit() # Important!
# OR use context manager
from contextlib import contextmanager
@contextmanager
def selenium_driver():
driver = webdriver.Chrome()
try:
yield driver
finally:
driver.quit()
# Usage
with selenium_driver() as driver:
driver.get("https://example.com")
# Test code
|
5. Use Headless Mode for CI/CD
1
2
3
4
5
6
| options = Options()
options.add_argument("--headless") # No window
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Chrome(options=options)
|
6. Descriptive Test Names
1
2
3
4
5
6
7
8
9
| # ✅ GOOD: Clear test names
def test_user_can_login_with_valid_credentials():
pass
def test_error_shown_for_invalid_email():
pass
def test_cart_item_removed_when_delete_clicked():
pass
|
7. Logging & Screenshots
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def test_with_logging(driver):
try:
logger.info("Starting test")
driver.get("https://example.com")
logger.info(f"Page loaded: {driver.title}")
element = driver.find_element(By.ID, "element")
logger.info("Element found")
except Exception as e:
logger.error(f"Test failed: {e}")
driver.save_screenshot(f"error_{datetime.now()}.png")
raise
|
8. Data-Driven Testing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| import pytest
# Test data
test_data = [
("valid@email.com", "password123"),
("invalid@email", "short"),
("", "password"),
]
@pytest.mark.parametrize("email,password", test_data)
def test_login_with_different_credentials(driver, email, password):
page = LoginPage(driver)
page.login(email, password)
# assertions
|
Kesimpulan
Key Takeaways
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| ✅ SELENIUM WEBDRIVER OVERVIEW:
✓ Open source & free
✓ Multi-browser support
✓ Multiple language support
✓ Easy to learn & use
✓ Large community & resources
✓ Industry standard
✓ Powerful & flexible
✅ INSTALLATION:
✓ pip install selenium
✓ pip install webdriver-manager
✓ No manual driver management needed
✅ CORE CONCEPTS:
✓ Finding elements (By ID, CSS, XPath)
✓ Interacting with elements (click, type, submit)
✓ Waiting for elements (explicit, implicit)
✓ Navigating pages
✓ Window & tab management
✓ Taking screenshots
✅ BEST PRACTICES:
✓ Use Page Object Model
✓ Explicit waits always
✓ Exception handling
✓ Proper cleanup
✓ Descriptive naming
✓ Logging & screenshots
✓ Data-driven testing
|
Next Steps
- Install Selenium:
pip install selenium webdriver-manager - Try Examples: Run the provided code examples
- Practice: Build tests for your own website
- Learn POM: Implement Page Object Model
- CI/CD Integration: Setup automated testing
- Advanced Topics: Parallel execution, Grid, Appium
Resources
Happy Selenium Testing! 🚀