完成- -个完整的python程序开放满分40分。类型爬虫类或游戏类基本要求 1能正常运行无报错; 2、能实现预定的功能; 3、自行编写不得在网上拷贝
这里提供一个简单的爬虫程序示例,可以获取指定网站的新闻标题和链接,并保存到本地文件中。
import requests from bs4 import BeautifulSoup
url = 'https://news.baidu.com/' res = requests.get(url) res.encoding = 'utf-8' soup = BeautifulSoup(res.text, 'html.parser')
news_list = [] for news in soup.select('.ulist.focuslistnews.topli'): title = news.select_one('a').text.strip() link = news.select_one('a')['href'] news_list.append({'title': title, 'link': link})
with open('news.txt', 'w', encoding='utf-8') as f: for news in news_list: f.write(news['title'] + '\n') f.write(news['link'] + '\n\n')
print('News saved to news.txt')
程序说明:
- 首先导入需要的库:requests和BeautifulSoup;
- 定义要爬取的网站URL,并使用requests库获取网页内容;
- 使用BeautifulSoup库解析HTML页面,并提取新闻标题和链接;
- 将标题和链接保存到一个列表中;
- 将列表内容保存到本地文件中;
- 打印提示信息
原文地址: http://www.cveoy.top/t/topic/gEa7 著作权归作者所有。请勿转载和采集!