0

Всем добрый день. Есть скрипт на Python, который парсит эту станицу:

https://www.flashscore.ru/match/llD7mNQ3/#odds-comparison;over-under;full-time

а именно тоталы 2.5 больше и меньше (при наведении можно увидеть цифры, вот он их и парсит). Но есть исключения, когда такой страницы просто нет. Как это исключение можно было реализовать, чтобы не вылезала ошибка например с этой ссылкой:

https://www.flashscore.ru/match/E59SH3xO/#odds-comparison;over-under;full-time

Сам код с первой ссылкой:

import re
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def wait_to_find_by(driver, wait, value=None, find="", by=By.ID, text=True):
    try:
        element = wait.until(
            EC.text_to_be_present_in_element((by, value), find)
        )
        element = driver.find_element(by=by, value=value)
        if text:
            return element.text
        return element
    except TimeoutException:
        driver.quit()
        raise Exception(f"Element not found after {wait._timeout} sec of waiting")
    except Exception as e:
        driver.quit()
        raise e


def main(sec_wait):
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, sec_wait)

    driver.get("https://www.flashscore.ru/match/llD7mNQ3/#odds-comparison;over-under;full-time")

    wait_to_find_by(driver, wait, "odds_ou_2.5")

    soup = BeautifulSoup(driver.page_source, 'lxml')
    total_25 = (soup.find("table", id="odds_ou_2.5")
        .find_all("tr", class_=["odd", "even"]))


    data = []
    for bookmaker in total_25:
        link = bookmaker.find("a", class_="elink").get("href")
        if link.find("453") == -1:
           continue
        data.append([
            bookmaker.find("span", class_=["up"]),
            bookmaker.find("span", class_=["down"])
        ])

    if len(data) != 1:
        raise Exception("there is no needable bookmaker")
    else:
        element_up, element_down = data[0]

    data_up = re.split(r"\[.+\]", element_up.get("eu"))
    data_down = re.split(r"\[.+\]", element_down.get("eu"))

    print("up:", " >> ".join(data_up))
    print("down:", " >> ".join(data_down))


if __name__ == "__main__":
    main(10)

Вот код со второй ссылкой:

import re
import time
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


def wait_to_find_by(driver, wait, value=None, find="", by=By.ID, text=True):
    """Finds an element by By object and an expectation for
    checking if the given text is present in the specified element.
    If no match was found within the specified time, an Exception is raised.

    inputs:
        driver - instance of the selenium.webdriver.some_class.
        wait - instance of the selenium.webdriver.support.ui.WebDriverWait.
        value[None] - The By object of the element to be found.
        find[""] - the text that must be present in the element.
        by[By.ID] - selenium.webdriver.common.by.By object.
        text[True] - if False, then returns the element itself, otherwise - element.text.
    """
    try:
        element = wait.until(
            EC.text_to_be_present_in_element((by, value), find)
        )
        element = driver.find_element(by=by, value=value)
        if text:
            return element.text
        return element
    except TimeoutException:
        driver.quit()
        raise Exception(f"Element not found after {wait._timeout} sec of waiting")
    except Exception as e:
        driver.quit()
        raise e


def main(sec_wait):
    driver = webdriver.Chrome()
    wait = WebDriverWait(driver, sec_wait)


    driver.get("https://www.flashscore.ru/match/E59SH3xO/#odds-comparison;over-under;full-time")

    wait_to_find_by(driver, wait, "odds_ou_2.5")

    soup = BeautifulSoup(driver.page_source, 'lxml')
    total_25 = (soup.find("table", id="odds_ou_2.5")
        .find_all("tr", class_=["odd", "even"]))


    data = []
    for bookmaker in total_25:
        link = bookmaker.find("a", class_="elink").get("href")
        if link.find("453") == -1:
           continue
        data.append([
            bookmaker.find("span", class_=["up"]),
            bookmaker.find("span", class_=["down"])
        ])

    if len(data) != 1:
        raise Exception("there is no needable bookmaker")
    else:
        element_up, element_down = data[0]

    data_up = re.split(r"\[.+\]", element_up.get("eu"))
    data_down = re.split(r"\[.+\]", element_down.get("eu"))

    print("up:", " >> ".join(data_up))
    print("down:", " >> ".join(data_down))


if __name__ == "__main__":
    main(10)

Со вторым кодом выводит ошибку, так как во второй ссылке нет информации про коэффициенты:

    raise TimeoutException(message, screen, stacktrace)
selenium.common.exceptions.TimeoutException: Message: 


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/iljal/PycharmProjects/google_sheets/nnthfnh.py", line 77, in <module>
    main(10)
  File "C:/Users/iljal/PycharmProjects/google_sheets/nnthfnh.py", line 47, in main
    wait_to_find_by(driver, wait, "odds_ou_2.5")
  File "C:/Users/iljal/PycharmProjects/google_sheets/nnthfnh.py", line 34, in wait_to_find_by
    raise Exception(f"Element not found after {wait._timeout} sec of waiting")
Exception: Element not found after 10 sec of waiting

Как вклчить в код это исключение, чтобы просто ничего не выводило или выводило сообщение, что этой информации нет на сайте?

введите сюда описание изображения

1 ответ 1

2

У вас в коде есть похожий блок, так что импорт уже делать не надо.

from selenium.common.exceptions import TimeoutException

try:
 #Тут код запроса и поиска

except TimeoutException:
 print('Ой, ой, ой, всё сломалось')

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.