You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python爬虫代码仅输出单条或前3条BBC新闻头条?

BBC头条爬虫修改方案

原代码通过find_all('h3')拿到的是页面内按出现顺序排列的所有头条标题列表,只要对这个列表做截取就能实现需求:


方案1:仅输出主头条

直接取列表的第一个元素即可,增加非空判断避免页面结构变动导致报错:

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')
if headlines:
    print(headlines[0].text.strip())

方案2:输出前3条头条

对列表做切片操作取前3个元素遍历即可,当页面头条不足3条时会自动输出所有可抓取到的头条:

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[:3]:
    print(x.text.strip())

内容的提问来源于stack exchange,提问作者Olt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 12:45:08