💻 Примеры: локаторы на suninjuly.github.io/cats.html

← К оглавлению урока

⚡ Примеры: CSS и XPath на cats.html

# conftest.py
@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    driver.get("https://suninjuly.github.io/cats.html")
    yield driver
    driver.quit()

# test_cats.py
def test_header(driver):
    h = driver.find_element(By.TAG_NAME, "h1")
    assert h.text == "Cat memes"

def test_cards_count(driver):
    cards = driver.find_elements(By.CSS_SELECTOR, ".col-sm-4")
    assert len(cards) == 6

Тестовая страница

Все примеры используют страницу suninjuly.github.io/cats.html — галерею карточек котов. На ней 6 карточек, каждая с изображением, названием, временем и кнопкой View.

Структура проекта

tests/
├── conftest.py        # фикстура driver
└── test_cats.py       # тесты

Фикстура (conftest.py)

# conftest.py
import pytest
from selenium import webdriver

@pytest.fixture
def driver():
    driver = webdriver.Chrome()
    driver.maximize_window()
    driver.get("https://suninjuly.github.io/cats.html")
    yield driver
    driver.quit()

Пример 1: поиск элементов с CSS-селекторами

# test_cats.py
from selenium.webdriver.common.by import By

class TestCSSLocators:

    def test_header_text(self, driver):
        # By.TAG_NAME — первый h1 на странице
        header = driver.find_element(By.TAG_NAME, "h1")
        assert header.text == "Cat memes"

    def test_time_of_first_card(self, driver):
        # :nth-child(1) — первая карточка, small — время
        time_el = driver.find_element(
            By.CSS_SELECTOR, ".col-sm-4:nth-child(1) small"
        )
        assert time_el.text == "9 mins"

    def test_last_card_name(self, driver):
        # :nth-child(6) — шестая (последняя) карточка, p — название
        last_name = driver.find_element(
            By.CSS_SELECTOR, ".col-sm-4:nth-child(6) p"
        )
        assert last_name.text == "I love you so much"

    def test_album_text(self, driver):
        # By.TAG_NAME — первый тег strong на странице
        album = driver.find_element(By.TAG_NAME, "strong")
        assert album.text == "Cats album"

Пример 2: поиск по CSS с описанием локаторов

# test_css_detailed.py
from selenium.webdriver.common.by import By

def test_css_locators(driver):
    # По ID — изображение с id="bullet"
    img_bullet = driver.find_element(By.CSS_SELECTOR, "#bullet")
    assert img_bullet.is_displayed()

    # По классу — все элементы с card-text
    card_texts = driver.find_elements(By.CSS_SELECTOR, ".card-text")
    assert len(card_texts) == 6

    # По атрибуту name — article[name="moto"]
    article = driver.find_element(By.CSS_SELECTOR, "article[name='moto']")
    assert article is not None

    # По вложенности — кнопка внутри .btn-group
    view_btn = driver.find_element(By.CSS_SELECTOR, ".btn-group button")
    assert view_btn.text == "View"

    # CSS с > (прямой потомок) — p сразу внутри .card-body
    card_p = driver.find_element(By.CSS_SELECTOR, ".card-body > p")
    assert card_p is not None

Пример 3: поиск с XPath

# test_xpath.py
from selenium.webdriver.common.by import By

def test_xpath_locators(driver):
    # По ID
    img = driver.find_element(By.XPATH, '//*[@id="bullet"]')
    assert img.is_displayed()

    # По атрибуту name
    article = driver.find_element(By.XPATH, '//p[@name="Vova"]')
    assert article is not None

    # По точному тексту кнопки
    view_btn = driver.find_element(By.XPATH, '//button[text()="View"]')
    assert view_btn.text == "View"

    # По частичному совпадению атрибута src
    cat_img = driver.find_element(By.XPATH, '//img[contains(@src, "serious_cat")]')
    assert cat_img.is_displayed()

    # XPath с // — кнопки где угодно внутри .card-body
    buttons = driver.find_elements(
        By.XPATH, '//div[@class="card-body"]//button'
    )
    assert len(buttons) > 0

Пример 4: is_displayed() — проверка видимости

# test_visibility.py
from selenium.webdriver.common.by import By

class TestVisibility:

    def test_first_card_is_displayed(self, driver):
        first_card = driver.find_element(
            By.CSS_SELECTOR, ".col-sm-4:nth-child(1)"
        )
        assert first_card.is_displayed()

    def test_photo_icon_is_displayed(self, driver):
        # SVG-иконка фотоаппарата
        photo_icon = driver.find_element(By.TAG_NAME, "svg")
        assert photo_icon.is_displayed()

Пример 5: find_elements() — работа со списком

# test_find_elements.py
from selenium.webdriver.common.by import By

class TestFindElements:

    def test_image_quantity(self, driver):
        images = driver.find_elements(By.TAG_NAME, "img")
        assert len(images) == 6

    def test_cards_quantity(self, driver):
        cards = driver.find_elements(By.CSS_SELECTOR, ".col-sm-4")
        assert len(cards) == 6

    def test_all_cards_displayed(self, driver):
        cards = driver.find_elements(By.CSS_SELECTOR, ".col-sm-4")
        for card in cards:
            assert card.is_displayed()

    def test_all_images_displayed(self, driver):
        images = driver.find_elements(By.TAG_NAME, "img")
        for img in images:
            assert img.is_displayed()

    def test_cards_with_index(self, driver):
        """Перебор карточек с выводом диагностики"""
        cards = driver.find_elements(By.CSS_SELECTOR, ".col-sm-4")
        for index, card in enumerate(cards, start=1):
            displayed = card.is_displayed()
            print(f"Карточка {index}: '{card.text[:20]}...', видна: {displayed}")
            assert displayed, f"Карта {index} не отображается"

Запуск тестов

# Запуск всех тестов
python -m pytest tests/ -v

# Запуск одного файла
python -m pytest tests/test_cats.py -v

# Запуск одного теста
python -m pytest tests/test_cats.py::TestCSSLocators::test_header_text -v