帮我写一个获取世界新闻的Python程序
时间: 2023-12-01 11:02:50 浏览: 29
好的,以下是一个获取世界新闻的Python程序示例:
```python
import requests
from bs4 import BeautifulSoup
# 定义一个获取新闻的函数
def get_news():
url = "https://www.bbc.com/news/world"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
news_list = soup.find_all("div", class_="gs-c-promo-body gel-1/2@xs gel-1/1@m gs-u-mt@m")
for news in news_list:
title = news.find("h3", class_="gs-c-promo-heading__title gel-pica-bold nw-o-link-split__text").text.strip()
summary = news.find("p", class_="gs-c-promo-summary gel-long-primer gs-u-mt nw-c-promo-summary").text.strip()
link = news.find("a", class_="gs-c-promo-heading nw-o-link nw-o-link--no-visited-state")["href"]
print(title)
print(summary)
print(link)
print("")
# 调用函数获取新闻
get_news()
```
这个程序使用了`requests`和`BeautifulSoup`库来发送HTTP请求和解析HTML页面。它首先定义了一个`get_news`函数,该函数会向BBC新闻网站发送请求,并使用`BeautifulSoup`解析页面内容。然后,它从页面中提取新闻标题、摘要和链接,并将它们打印出来。
你可以在函数中修改URL和选择不同的HTML元素来提取其他新闻网站的新闻。