写一个爬取图片网站的照片名称和链接,并且把它保存为csv文件,在利用Python方法调整里面内容不要超出单元格。
一:依赖导入与基础对象初始化
功能:导入程序所需的所有库,创建窗口、网页视图、CSV处理器等基础工具对象,为后续操作铺路。
aardio
import web.view
import console;
import string.html;
import string.csv
import win.ui;
import py3;
var winform = win.form(text="简单爬取网站图片链接和名称")
var wb = web.view(winform);
var csv = string.csv(',');
var headers = {"类型", "标题", "链接"};
csv.push(headers)
console.log('爬取数据中...')
URL列表生成
功能:根据目标网站的分页规则,生成需要爬取的所有页面URL,返回URL列表供后续爬取用。
aardio
function loop(){
var urllist = {};
for(page=1;10;1){
var url = "https://haowallpaper.com/?isSel=false&page=" +page
table.push(urllist,url)
}
return urllist;
}
数据爬取
功能:接收生成的URL列表,逐个页面加载、解析HTML,提取图片/视频的"类型、标题、链接",整理成结构化数据并返回。
aardio
function Crawl(){
var dataList = {};
for(i=1;#loop();1){
var url = loop()[i];
var response = wb.go (url)
if(response !== 0){
html = wb.html;
var htmlDoc = string.html( html )
var div_label = htmlDoc.queryEles( tagName = "div" );
var main_label = div_label[1].queryEles( tagName = "main" );
var div1_label = main_label[1].queryEles( tagName = "div" );
var div2_label = div1_label[3].queryEles( tagName = "div" );
var div3_label = div2_label[1].queryEles( tagName = "div" );
var div4_label = div3_label[1].queryEles( tagName = "div" );
var img_label = div4_label[1].queryEles( tagName = "img" );
var video_label = div4_label[1].queryEles( tagName = "video" );
// 整理数据:把图片、视频信息合并成字典,存入 dataList
for(k, value in img_label){
// 构造一个字典,包含标题、链接、类型(图片)
var imgDict = {
"类型": "图片",
"标题": value.title,
"链接": value.src
};
table.push(dataList, imgDict);
}
for(k, v in video_label){
// 构造一个字典,包含标题、链接、类型(视频)
var videoDict = {
"类型": "视频",
"标题": v.title,
"链接": v.src
};
table.push(dataList, videoDict); // 加入最终列表
}
}
}
return dataList;
}
模数据保存
功能:接收爬取到的结构化数据,按CSV表头顺序写入数据,最终保存为本地CSV文件,并提示保存结果。
aardio
var dataList = Crawl();
for(i=1;#dataList;1){
var row = {};
for(k,v in headers){
table.push(row,dataList[i][v])
}
csv.push(row)
}
var save = csv.save('products.csv')
if(save !== 0){
console.log('保存成功')
}
else {
console.log('保存失败')
}
CSV转格式化Excel
功能:调用Python代码,将保存的CSV文件转换为格式美观的Excel文件,并设置单元格对齐、列宽、行高等样式。
aardio
function py_method(){
var pyCode = /**
import csv
from openpyxl import Workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter
def format_csv_to_excel():
# 创建Excel工作簿
wb = Workbook()
ws = wb.active
# 替换的CSV文件路径
input_csv = "products.csv"
# 输出的Excel文件路径
output_excel = "formatted_data.xlsx"
# 读取CSV并写入Excel
with open(input_csv, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
for row in reader:
ws.append(row)
# 1. 设置单元格格式:居中对齐、自动换行、内边距
for row in ws.iter_rows():
for cell in row:
# 设置居中对齐(水平和垂直方向)、自动换行
# indent=3 表示缩进3个单位,模拟内边距效果
cell.alignment = Alignment(
horizontal='center', # 水平居中
vertical='center', # 垂直居中
wrapText=True, # 自动换行
indent=3 # 缩进3个单位,实现内容离边界的距离
)
# 2. 精准计算列宽(区分中英文)
for col in ws.columns:
col_idx = col[0].column
col_letter = get_column_letter(col_idx)
max_width = 0
for cell in col:
if not cell.value:
continue
text = str(cell.value)
# 计算字符宽度:中文≈2个单位,英文/数字≈1个单位
width = 0
for char in text:
if '\u4e00' <= char <= '\u9fff': # 中文字符范围
width += 2
else:
width += 1
# 保留最大宽度,考虑缩进带来的额外宽度需求
if width > max_width:
max_width = width
# 设置列宽(增加4个单位余量,因为有缩进)
ws.column_dimensions[col_letter].width = max_width + 4
# 3. 自动调整行高(根据换行数量)
for row in ws.iter_rows():
max_height = 30 # 基础行高
for cell in row:
if cell.value:
# 计算换行次数(包括自动换行产生的)
lines = str(cell.value).count('\n') + 1
# 每行高度约为30(根据实际字体大小调整)
row_height = lines * 30
if row_height > max_height:
max_height = row_height
ws.row_dimensions[cell.row].height = max_height
# 保存文件
wb.save(output_excel)
print(f"转换完成!文件已保存至:{output_excel}")
**/
// 执行 Python 代码
py3.exec(pyCode)
var aa = py3.main.format_csv_to_excel();
if(aa !== 0){
console.log('调整csv内容成功,转换为Excel文件')
}
else {
console.log('调整csv内容失败')
}
}
py_method()
console.pause()
注:此代码主要注重csv文件的学习,只能爬取代码中的网站,需要爬取其他网站的可以修改里面 'tagName'的值。
aardio 新手交流学习群,一起学习的进
qq群号:697197055