[英]How do I reset the outputs generated from my ipywidget command button so that only the updated DataFrame is displayed?
[英]How do I modify the code so that it only outputs one headline from the news instead of all of them?
import requests
from bs4 import BeautifulSoup
url='https://www.bbc.co.uk/news'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
headlines = soup.find('body').find_all('h3')
for x in headlines:
print(x.text.strip())
问题是它打印出 BBC 文章的所有标题,但是,我只想能够更改代码,使其仅输出主要标题或前 3 个标题。 有谁知道如何帮助我解决这个问题?
你可以这样做。
将k
替换为您希望显示的任意数量的标题。
for x in headlines[:k]:
print(x.text.strip())
enumerate()
for idx, val in enumerate(headlines, start=1):
if idx <= k:
print(val.text.strip())
你为什么不使用计数器
for counter, x in enumerate(headlines):
if counter >= 2:
break
print(x.text.strip())
编辑:感谢@Matiiss 告知我这种计数器方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.