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.
tentest/doc/DjangoBlog/djangoblog/spider_notify.py

41 lines
1.8 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 # 导入日志模块,用于记录通知过程中的信息和错误
import requests # 导入requests库用于发送HTTP请求与搜索引擎API交互
from django.conf import settings # 导入Django配置用于获取百度推送API地址等配置项
#wr 初始化日志记录器(指定记录器名称为当前模块)
logger = logging.getLogger(__name__)
class SpiderNotify():
"""
wr搜索引擎通知工具类用于向搜索引擎如百度推送网站新内容的URL
帮助搜索引擎快速发现并收录新页面提升SEO效率
"""
@staticmethod
def baidu_notify(urls):
"""
wr向百度搜索引擎推送URL使用百度链接提交API
百度会根据推送的URL优先抓取和收录页面
:param urls: 需要推送的URL列表如文章详情页链接
"""
try:
#wr 将URL列表转换为百度API要求的格式每行一个URL用换行符拼接
data = '\n'.join(urls)
#wr 发送POST请求到百度推送APIAPI地址从Django配置中获取
result = requests.post(settings.BAIDU_NOTIFY_URL, data=data)
#wr 记录API返回结果便于监控推送是否成功
logger.info(result.text)
except Exception as e:
#wr 记录推送过程中的异常如网络错误、API地址错误等
logger.error(e)
@staticmethod
def notify(url):
"""
wr通用通知方法封装百度推送逻辑便于后续扩展其他搜索引擎
目前仅实现百度推送,可根据需求添加谷歌、必应等其他引擎的推送逻辑
:param url: 需要推送的单个URL或URL列表根据实际调用场景调整
"""
#wr 调用百度推送方法
SpiderNotify.baidu_notify(url)