这里提供一个简单的爬虫程序示例,可以获取指定网站的新闻标题和链接,并保存到本地文件中。

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')

程序说明:

  1. 首先导入需要的库:requests和BeautifulSoup;
  2. 定义要爬取的网站URL,并使用requests库获取网页内容;
  3. 使用BeautifulSoup库解析HTML页面,并提取新闻标题和链接;
  4. 将标题和链接保存到一个列表中;
  5. 将列表内容保存到本地文件中;
  6. 打印提示信息
完成- -个完整的python程序开放满分40分。类型爬虫类或游戏类基本要求 1能正常运行无报错; 2、能实现预定的功能; 3、自行编写不得在网上拷贝

原文地址: http://www.cveoy.top/t/topic/gEa7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录