猿问

确定 HTML 项目是否具有 Python 和 BeautifulSoup 的类

我想确定一个 li 项目是否具有 .corsa-yes 类。如果是,我想附加到数组“状态”:“活动”。数据是从这个网站上抓取的 我已经尝试了以下代码,但我得到了


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" 

                })


墨色风雨
浏览 157回答 1
1回答

慕容森

错误信息TypeError:“NoneType”类型的参数不可迭代是因为元素有no class,你需要先检查它是否存在或与数组进行比较if next_li.get("class") == ["corsa-yes"]:# or check it firstif next_li.get("class") and "corsa-yes" in next_li.get("class"):我的变化'STATUS': "active",以'ACTIVE_TIME': '10:35'和完整代码departure_time = []active_time = Nonefor 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']}]
随时随地看视频慕课网APP

相关分类

Python
我要回答