最佳答案
引言
跟著軟體開辟的壹直進步,主動化測試已成為進步軟體品質、晉升開辟效力的重要手段。Selenium Python因其富強的功能跟易用性,成為主動化測試範疇的熱點東西。本文將經由過程對Selenium Python的實戰案例剖析,提醒主動化測試之道。
一、Selenium Python簡介
Selenium是一個開源的主動化測試東西,支撐多種編程言語,包含Python。它容許測試人員模仿用戶在瀏覽器中的操縱,如點擊、輸入、拖動等,從而實現對Web利用順序的主動化測試。
二、Selenium Python情況搭建
- 安裝Python:從官網下載Python安裝包,按照提示停止安裝。
- 安裝Selenium庫:打開命令行,輸入
pip install selenium
停止安裝。 - 安裝WebDriver:根據所利用的瀏覽器,下載對應的WebDriver。比方,對Chrome瀏覽器,下載ChromeDriver。
三、Selenium Python基本操縱
- 打開瀏覽器:利用
webdriver.Chrome()
創建一個WebDriver實例,打開瀏覽器。 - 定位元素:利用
find_element_by_*
方法定位頁面元素,如find_element_by_id()
、find_element_by_name()
、find_element_by_xpath()
等。 - 元素操縱:對定位到的元素停止操縱,如點擊、輸入、獲取屬性等。
- 等待戰略:利用
WebDriverWait
跟expected_conditions
實現頁面載入等待。
四、實戰案例剖析
案例一:登錄功能測試
- 打開登錄頁面。
- 輸入用戶名跟密碼。
- 點擊登錄按鈕。
- 驗證登錄成功。
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("http://www.example.com/login")
username = driver.find_element_by_id("username")
password = driver.find_element_by_id("password")
login_button = driver.find_element_by_id("login_button")
username.send_keys("your_username")
password.send_keys("your_password")
login_button.click()
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "user_profile")))
print("登錄成功")
案例二:購物車功能測試
- 增加商品到購物車。
- 刪除購物車中的商品。
- 驗證購物車數量。
from selenium.webdriver.common.action_chains import ActionChains
# ...(省略打開瀏覽器跟定位元素代碼)
add_to_cart_button = driver.find_element_by_id("add_to_cart_button")
ActionChains(driver).click(add_to_cart_button).perform()
delete_button = driver.find_element_by_id("delete_button")
ActionChains(driver).click(delete_button).perform()
WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "cart_count")))
print("購物車數量驗證成功")
案例三:數據採集
- 採集網頁上的商品信息。
- 保存數據到當地或材料庫。
from selenium.webdriver.common.keys import Keys
# ...(省略打開瀏覽器跟定位元素代碼)
product_price = driver.find_element_by_id("product_price").text
product_name = driver.find_element_by_id("product_name").text
# 保存數據到當地
with open("product_info.txt", "w") as f:
f.write(f"商品稱號:{product_name}\n")
f.write(f"商品價格:{product_price}\n")
# 保存數據到材料庫(以SQLite為例)
import sqlite3
conn = sqlite3.connect("product_info.db")
c = conn.cursor()
c.execute("CREATE TABLE IF NOT EXISTS products (name TEXT, price TEXT)")
c.execute("INSERT INTO products (name, price) VALUES (?, ?)", (product_name, product_price))
conn.commit()
conn.close()
五、總結
經由過程以上實戰案例剖析,我們可能看到Selenium Python在主動化測試範疇的富強才能。在現實項目中,我們可能根據須要機動應用Selenium Python,進步測試效力跟覆蓋率。壹直積聚實戰經驗,控制主動化測試之道。