Освоение автоматизации Selenium: изучение мощных методов на примерах кода

Selenium – популярная платформа с открытым исходным кодом, используемая для автоматизации веб-браузеров. Он предоставляет ряд функций для моделирования действий пользователя, взаимодействия с веб-элементами и выполнения различных задач тестирования и очистки данных. В этой статье мы рассмотрим различные методы использования Selenium с циклами for для улучшения автоматизации тестирования и процессов очистки веб-страниц. Давайте рассмотрим эти методы на примерах кода.

Метод 1: перебор списка элементов

from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a webpage
driver.get('https://www.example.com')
# Find all elements with a specific class
elements = driver.find_elements_by_class_name('my-element-class')
# Iterate through the elements and perform actions
for element in elements:
    # Perform actions on each element
    element.click()
    # ... additional actions
# Close the WebDriver
driver.quit()

Метод 2: цикл по диапазону значений

from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a webpage
driver.get('https://www.example.com')
# Loop through a range of values
for i in range(1, 6):
    # Construct dynamic XPath using the value
    xpath = f'//*[@id="item-{i}"]'

    # Find the element using the XPath
    element = driver.find_element_by_xpath(xpath)

    # Perform actions on the element
    element.click()
    # ... additional actions
# Close the WebDriver
driver.quit()

Метод 3. Вложенные циклы для сложных сценариев

from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a webpage
driver.get('https://www.example.com')
# Loop through rows and columns of a table
for row in range(1, 5):
    for col in range(1, 4):
        # Construct dynamic XPath using row and column values
        xpath = f'//*[@id="table"]/tr[{row}]/td[{col}]'

        # Find the element using the XPath
        element = driver.find_element_by_xpath(xpath)

        # Perform actions on the element
        element.click()
        # ... additional actions
# Close the WebDriver
driver.quit()

Метод 4. Использование циклов while для динамических сценариев

from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a webpage
driver.get('https://www.example.com')
# Set a condition to exit the loop
condition = True
while condition:
    # Check if the desired element is present
    if driver.find_elements_by_id('element-id'):
        # Perform actions on the element
        element = driver.find_element_by_id('element-id')
        element.click()

        # Update the condition to exit the loop
        condition = False
    else:
        # Perform other actions or wait for the element to appear
        # ...
# Close the WebDriver
driver.quit()