You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog-Maintenance-Anal.../src/spider_notify.py

49 lines
2.0 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 导入日志模块,用于记录通知过程中的信息和错误
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):
"""
向百度搜索引擎提交链接的静态方法
通过百度链接提交APIBAIDU_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)