给需要做seo的小伙伴,生成sitemap文件给搜索引擎。
支持修改爬取网站
支持修改爬取深度
支持修改爬取总数
开箱即用
#使用方式
#直接运行 记得给权限
./crawl.sh
#后台运行
nohup ./crawl.sh &
#!/bin/bash
# 定义要爬取的网站链接
website_url="https://www.oknovel.net"
# 定义爬取深度(基础链接上最多爬取数)
max_depth=3
# 定义总爬取链接数
total_links=40000
# 定义保存链接的输出文件目录
output_dir="./"
# 创建保存链接的输出文件目录(如果不存在)
mkdir -p "$output_dir"
# 获取当前日期和时间,用于文件名
current_datetime=$(date "+%Y%m%d_%H%M%S")
# 获取网站的主机名,用于文件名
hostname=$(echo $website_url | awk -F/ '{print $3}')
# 定义保存链接的输出文件名
output_file="${output_dir}/${hostname}_${total_links}_${current_datetime}.txt"
# 设置超时时间(单位:秒)
timeout_seconds=10
# 使用数组存储已爬取的链接,用于去重
declare -a crawled_links
# 全局变量,用于记录已爬取的链接数量
global_crawled_count=0
# 验证链接的有效性并保存链接的函数
validate_and_save_link() {
local link=$1
# 从响应头信息中提取状态码
status_code=$(curl --insecure -s -o /dev/null -w "%{http_code}\n" ${website_url})
# 如果状态码为200,则链接有效,输出并保存
if [ "$status_code" == "200" ]; then
echo "$link"
echo "$link" >> "$output_file"
global_crawled_count=$((global_crawled_count + 1))
else
echo "链接无效:$link (状态码:$status_code)"
fi
}
# 递归爬取网站链接的函数
crawl_links() {
local url=$1
local depth=$2
# 如果深度为0,则返回
if [ $depth -eq 0 ]; then
return
fi
# 使用wget命令爬取当前链接的页面内容
page_content=$(wget --no-check-certificate --quiet -O - "$url")
# 提取页面中的链接,并验证有效性后输出到控制台和文件
while read -r link; do
# 如果链接以http或https开头,且包含网站主机名,则输出并保存
if [[ $link != "http"* ]]; then
link="$website_url$link"
fi
# 检查链接是否为静态资源链接
if [[ $link == "$website_url"* && $link != *".css"* && $link != *".js"* && $link != *".png"* && $link != *".jpg"* && $link != *".gif"* && $link != *".ico"* ]]; then
# 检查链接是否已经爬取过(去重)
if [[ ! " ${crawled_links[@]} " =~ " ${link} " ]]; then
crawled_links+=("$link")
# 检查是否达到总链接数上限
if [ $global_crawled_count -lt $total_links ]; then
validate_and_save_link "$link"
if [ "$status_code" == "200" ]; then
crawl_links "$link" $((depth - 1))
fi
fi
fi
fi
done <<< "$(echo "$page_content" | grep -oE 'href="([^"#]+)"' | cut -d'"' -f2)"
}
# 执行爬取
echo "开始爬取 $website_url,深度为 $max_depth,总链接数为 $total_links ..."
# 调用递归函数开始爬取
crawl_links "$website_url" $max_depth
恒哥成长日记第一篇文章《制作sitemap-bash脚本》-2024年02月13日 11:34:33