为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

墨色风雨 2021-09-28 13:56:56
我想确定一个 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"                 })
查看完整描述

1 回答

?
慕容森

TA贡献1853条经验 获得超18个赞

错误信息


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']}

]


查看完整回答
反对 回复 2021-09-28
  • 1 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号