乐闻世界logo
搜索文章和话题

How to Verify Tooltip Text with Selenium?

2024年7月4日 22:45

When using Selenium for automated testing, verifying tooltip text on the page (i.e., the information displayed when hovering over an element) is a common testing requirement. Here is a specific step-by-step guide and example demonstrating how to verify tooltip text using Selenium:

Steps:

  1. Locate the Element: First, identify the element on the page where you need to verify the tooltip.

  2. Hover Operation: Use Selenium's ActionChains to simulate hovering over the target element.

  3. Retrieve Tooltip Text: Obtain the tooltip text, which is typically stored in an HTML attribute such as title or dynamically generated via JavaScript.

  4. Verification Using Assertions: Compare the retrieved tooltip text with the expected value to confirm functionality.

Example:

Suppose we have a webpage with a button that displays the tooltip text 'Click me' when hovered. Below is a code example using Python and Selenium for automated testing:

python
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Launch Chrome browser driver = webdriver.Chrome() # Open the target webpage driver.get("http://example.com") # Wait for element to load element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "tooltip-button")) ) # Create ActionChains object and perform hover operation hover = ActionChains(driver).move_to_element(element) hover.perform() # Retrieve tooltip text tooltip_text = element.get_attribute("title") # Verify tooltip text using assertion assert tooltip_text == "Click me", "Tooltip text does not match expected value" # Close browser driver.quit()

Explanation:

In this example, we first import necessary modules and classes. We launch the Chrome browser using webdriver.Chrome() and access the test page via driver.get(). We use WebDriverWait and EC.presence_of_element_located to ensure the element is successfully located. We employ the ActionChains class to simulate hovering, then retrieve the element's title attribute using get_attribute("title"), assuming the tooltip is implemented via the title attribute. Finally, we use the assert statement to verify that the actual tooltip text matches the expected value.

By following this approach, we can effectively validate tooltip text on webpages, ensuring that UI element interaction feedback aligns with design specifications.

标签:Selenium