帮我写一个自动获取世界新闻的Python代码
时间: 2023-11-21 12:04:41 浏览: 32
以下是一个获取BBC新闻的Python代码示例:
```python
import requests
from bs4 import BeautifulSoup
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 gs-o-faux-block-link__overlay-link gel-pica-bold nw-o-link-split__anchor')['href']
print(title)
print(summary)
print(link)
print()
```
此代码使用了requests和BeautifulSoup库来获取和解析BBC新闻网站的内容。它首先发送一个请求到BBC新闻网站,然后使用BeautifulSoup将响应内容解析成HTML。
然后,它查找所有带有class为'gs-c-promo-body gel-1/2@xs gel-1/1@m gs-u-mt@m'的div元素,这些元素包含新闻的标题、摘要和链接。
最后,它循环遍历每个新闻元素,并从中提取标题、摘要和链接。它使用strip()方法来去除标题和摘要中的空格和换行符,并打印出来。