Определение, есть ли у элемента HTML класс с Python и BeautifulSoup - PullRequest
0 голосов
/ 28 декабря 2018

Я бы хотел определить, есть ли у элемента li класс .corsa-yes.Если да, я хотел бы добавить к массиву «STATUS»: «активный».Данные скопированы с этого сайта Я попробовал следующий код, но я получаю

if "corsa-yes" in next_li.get("class"):
TypeError: argument of type 'NoneType' is not iterable

Вот мой код

medmar_live_departures_table = list(soup.select('li.tratta'))
departure_time = []
    for li in medmar_live_departures_table:
        next_li = li.find_next_sibling("li")
        while next_li and next_li.get("data-toggle"):
            departure_time.append(next_li.strong.text)
            next_li = next_li.find_next_sibling("li")
        medmar_live_departures_data.append({
              'ROUTE' : li.text,
              'DEPARTURE TIME' : departure_time,
        })
             if "corsa-yes" in next_li.get("class"):
                medmar_live_departures_data.append({
                       'STATUS': "active" 
                })

1 Ответ

0 голосов
/ 29 декабря 2018

Сообщение об ошибке

TypeError: аргумент типа 'NoneType' не повторяется

, потому что элемент имеет no class, сначала нужно проверить, еслион существует или сравнивается с массивом

if next_li.get("class") == ["corsa-yes"]:
# or check it first
if next_li.get("class") and "corsa-yes" in next_li.get("class"):

Я изменяю 'STATUS': "active" на 'ACTIVE_TIME': '10:35' и полный код

departure_time = []
active_time = None
for li in medmar_live_departures_table:
    next_li = li.find_next_sibling("li")
    while next_li and next_li.get("data-toggle"):
        if next_li.get("class") == ["corsa-yes"]:
            active_time = next_li.strong.text
        departure_time.append(next_li.strong.text)
        next_li = next_li.find_next_sibling("li")
    medmar_live_departures_data.append({
          'ROUTE' : li.text,
          'ACTIVE_TIME' : active_time,
          'DEPARTURE TIME' : departure_time
    })
    departure_time = []

Результат

[
  {'ROUTE': 'ISCHIA » PROCIDA', 'ACTIVE_TIME': '10:35', 'DEPARTURE TIME': ['06:25', '10:35']},
  {'ROUTE': 'PROCIDA » NAPOLI', 'ACTIVE_TIME': '07:05', 'DEPARTURE TIME': ['07:05', '11:15']}
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...