[英]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.