簡體   English   中英

如何修改代碼,使其只輸出新聞中的一個標題而不是所有標題?

[英]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())

方法 2:使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM