Issue
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?
Solution
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())
Answered By - Ram
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.