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())
The issue is that it prints out all the headlines from BBC articles, however, I just want to be able to change the code so that it only outputs the main headline or the first 3 headlines. Does anyone know how to help me out with this problem?
CodePudding user response:
You can do like this.
Replace k
with whatever number of headlines you wish to display.
Method-1: List Slicing
for x in headlines[:k]:
print(x.text.strip())
Method-2: Using enumerate()
for idx, val in enumerate(headlines, start=1):
if idx <= k:
print(val.text.strip())
CodePudding user response:
why don't you use counters
for counter, x in enumerate(headlines):
if counter >= 2:
break
print(x.text.strip())
edited : thanks @Matiiss for informing me about this counter approach