如何在 python 的列表中编写异常代码?

How do i code an exception in a list in python?

我正在尝试创建一个新闻聚合器,使用 BeautifulSoup4 从纽约时报抓取头条新闻。

我想在网站上包含带有 h3 标签的前 15 个元素。然而,纽约时报上第9个带有h3标签的元素是广告。

我怎样才能把它包括进去?

这是我的代码:

ht_r = requests.get("https://www.nytimes.com/")
ht_soup = BeautifulSoup(ht_r.content, 'html.parser')
ht_headings = ht_soup.findAll('h3')
ht_headings = ht_headings[0:15]
ht_news = []

我试过了

del ht_headings[9]

但是,我收到此错误:

语法错误:无法删除函数调用

你可以试试:

ht_headings = ht_headings[:9] + ht_headings[10:]

也许只是循环遍历这样的列表?

import requests
from bs4 import BeautifulSoup

ht_r = requests.get("https://www.nytimes.com/")
ht_soup = BeautifulSoup(ht_r.content, 'html.parser')
ht_headings = ht_soup.findAll('h3')

output = []
i = 0 

for heading in ht_headings:
    if (i != 9 and i < 15):
        output.append(heading)

print(output)