我想请教一个问题用Python编写一个爬虫每天自动从陕西省政府采购网爬取生态环保类项目并保存至excel
以下是一个简单的Python爬虫示例,它可以从陕西省政府采购网上获取生态环保类项目信息,并将其保存在Excel文件中。要运行此脚本,您需要安装并导入以下库:requests,beautifulsoup4和openpyxl。
import requests
from bs4 import BeautifulSoup
import openpyxl
from datetime import date
# 设置请求头
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 设置爬取的网站链接和参数
url = 'http://www.sntba.com.cn/ecosphere/notice.html'
params = {'type': '1', 'noticeType': '1', 'endTime': str(date.today())}
# 发送GET请求并解析HTML代码
res = requests.get(url, headers=headers, params=params)
soup = BeautifulSoup(res.text, 'html.parser')
# 获取表格中的所有行和列
table = soup.find('table', {'class': 'table table-bordered table-hover table-responsive'})
rows = table.find_all('tr')
# 创建一个新的Excel工作表
wb = openpyxl.Workbook()
ws = wb.active
# 在第一行添加表头
ws.append(['项目名称', '采购人', '公告时间', '项目链接'])
# 遍历每一行并提取信息
for row in rows[1:]:
cols = row.find_all('td')
name = cols[1].text.strip()
buyer = cols[2].text.strip()
time = cols[3].text.strip()
link = cols[1].find('a')['href']
ws.append([name, buyer, time, link])
# 保存Excel文件
wb.save('ecosphere_projects.xlsx')
此脚本将在运行时从陕西省政府采购网获取生态环保类项目信息,并将其保存在名为“ecosphere_projects.xlsx”的Excel文件中。每次运行脚本时,它都会自动更新Excel文件并添加新的信息。您可以将此脚本定期运行,以便每天自动获取最新的信息。
原文地址: http://www.cveoy.top/t/topic/bkYA 著作权归作者所有。请勿转载和采集!