如何在python中对列表中的异常进行编码



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

我想在网站上包括前15个带有h3标签的元素。然而,《纽约时报》上第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]

然而,我得到了这个错误:

SyntaxError:无法删除函数调用

您可以尝试:

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)       

最新更新