# Как найти поврежденные ссылки в Selenium WebDriver?

### 🔹 Алгоритм поиска битых ссылок

1. Получить все элементы `<a>` (ссылки) на странице:

   ```python
   links = driver.find_elements("tag name", "a")
   ```
2. Для каждой ссылки достать атрибут `href`.
3. Проверить, что ссылка **не пуста** и **начинается с http/https**.
4. Отправить **HTTP-запрос** к этому URL (обычно методом `HEAD` или `GET`).
5. Проверить HTTP статус код ответа:
   * `200 OK` → ссылка рабочая
   * `404`, `500`, `403` и др. → ссылка повреждённая

```python
from selenium import webdriver
import requests

driver = webdriver.Chrome()
driver.get("https://example.com")

# Находим все ссылки <a>
links = driver.find_elements("tag name", "a")

for link in links:
    url = link.get_attribute("href")

    if not url:  # пустая или None
        print("❌ Пустая ссылка")
        continue

    try:
        # HEAD быстрее, чем GET (не загружает тело ответа)
        response = requests.head(url, allow_redirects=True, timeout=5)
        if response.status_code >= 400:
            print(f"❌ Битая ссылка: {url} | Код: {response.status_code}")
        else:
            print(f"✅ Рабочая ссылка: {url} | Код: {response.status_code}")
    except requests.exceptions.RequestException as e:
        print(f"⚠ Ошибка при проверке {url}: {e}")

driver.quit()


```

📌 Советы:

* Используй `requests.head()` → быстрее, чем `get()`.
* Добавляй `timeout` (иначе тест может зависнуть).
* Лучше собирать **и `<a>` и `<img>`**, потому что битая картинка → тоже ошибка.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kaze.gitbook.io/qa-theory/teoriya-avtomatizirovannogo-testirovaniya/selenium/kak-naiti-povrezhdennye-ssylki-v-selenium-webdriver.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
