[파이썬] Selenium 테스트 케이스 작성

Selenium is a powerful tool for automating web browsers. It allows you to write test cases that simulate user interactions with a web application. In this blog post, we will explore how to write Selenium test cases in Python using the Selenium WebDriver.

Setting Up Selenium WebDriver

Before we can start writing test cases, we need to set up the Selenium WebDriver in Python. Here are the steps to follow:

  1. Install Selenium package using pip:
    pip install selenium
    
  2. Download the appropriate web driver for the browser you want to automate. Selenium supports different web browsers like Chrome, Firefox, etc. Make sure to place the web driver executable in your system’s PATH.

  3. Import the necessary modules in your Python script:
    from selenium import webdriver
    
  4. Initialize the WebDriver object for the browser you want to automate:
    driver = webdriver.Chrome()  # For Chrome
    # driver = webdriver.Firefox()  # For Firefox
    

Writing Selenium Test Cases

Now that we have set up the Selenium WebDriver, let’s dive into writing some test cases. Test cases are written in a way that simulates user interactions with a web application. Here’s an example of a Selenium test case written in Python:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# Initialize the WebDriver object
driver = webdriver.Chrome()

# Navigate to the website
driver.get("https://www.example.com")

# Find an input element and enter text
search_input = driver.find_element_by_name("q")
search_input.send_keys("Selenium")

# Press Enter key to submit the search
search_input.send_keys(Keys.ENTER)

# Verify the search results
search_results = driver.find_elements_by_css_selector(".search-result")
assert len(search_results) > 0

# Close the browser
driver.quit()

In this example, we first import the necessary modules and initialize the WebDriver object for Chrome. Then, we navigate to a website (in this case, “https://www.example.com”) and find an input element to enter text. We use the Keys.ENTER constant to simulate pressing the Enter key to submit the search.

After that, we verify the search results by finding elements with the CSS selector “.search-result” and asserting that the number of results is greater than 0. Finally, we close the browser using the quit() method of the WebDriver object.

Conclusion

Writing Selenium test cases in Python allows us to automate the testing of web applications. With the Selenium WebDriver, we can simulate user interactions and verify the expected results. By following the steps outlined in this blog post, you can easily set up the Selenium WebDriver in Python and start writing your own test cases. Happy testing!