From d2f7647727f3d5517175151b4c48caf797fcd1cf Mon Sep 17 00:00:00 2001 From: LY Date: Sat, 18 Oct 2025 18:21:10 +0800 Subject: [PATCH] =?UTF-8?q?ly=5F=E7=AC=AC=E4=BA=94=E5=91=A8=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/spider_notify.py | 49 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/spider_notify.py diff --git a/src/spider_notify.py b/src/spider_notify.py new file mode 100644 index 0000000..65142d8 --- /dev/null +++ b/src/spider_notify.py @@ -0,0 +1,49 @@ +# 导入日志模块,用于记录通知过程中的信息和错误 +import logging + +# 导入requests库,用于发送HTTP请求(向搜索引擎提交链接) +import requests +# 导入Django项目配置,用于获取百度链接提交的URL(在settings.py中配置) +from django.conf import settings + +# 创建当前模块的日志记录器,用于输出通知相关的日志 +logger = logging.getLogger(__name__) + + +class SpiderNotify(): + """ + 搜索引擎爬虫通知类:用于向搜索引擎(当前仅百度)提交网站新链接 + 帮助搜索引擎快速发现并收录网站新增或更新的页面,提升SEO效果 + """ + + @staticmethod + def baidu_notify(urls): + """ + 向百度搜索引擎提交链接的静态方法 + 通过百度链接提交API(BAIDU_NOTIFY_URL),将新页面URL推送给百度爬虫 + + Args: + urls (list): 需要提交的URL列表(每个元素为一个页面的完整URL或相对URL) + """ + try: + # 将URL列表转换为以换行符分隔的字符串,符合百度API的提交格式要求 + data = '\n'.join(urls) + # 发送POST请求到百度链接提交URL,提交URL数据 + result = requests.post(settings.BAIDU_NOTIFY_URL, data=data) + # 记录百度返回的响应结果(成功时包含提交状态,用于调试和审计) + logger.info(result.text) + except Exception as e: + # 捕获请求过程中的所有异常(如网络错误、API地址错误等),记录错误日志 + logger.error(e) + + @staticmethod + def notify(url): + """ + 通用通知入口静态方法:统一调用百度链接提交方法 + 此处为简化设计,后续可扩展支持其他搜索引擎(如谷歌、必应) + + Args: + url (str/list): 单个URL字符串或URL列表(最终会转为列表提交给百度) + """ + # 调用百度链接提交方法,实现URL推送 + SpiderNotify.baidu_notify(url) \ No newline at end of file