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.
djangoBlogStudy/src/djangoblog/spider_notify.py

58 lines
2.6 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
from django.conf import settings
# 获取当前模块的日志记录器,用于输出日志信息
logger = logging.getLogger(__name__)
#wwc
class SpiderNotify():
"""
蜘蛛推送通知工具类用于向搜索引擎如百度主动推送网站新内容的URL
帮助搜索引擎更快发现和收录网页。
"""
#wwc
@staticmethod
def baidu_notify(urls):
"""
向百度搜索引擎推送一组URL链接主动抓取通知
使用百度提供的链接提交API将新发布的页面URL推送给百度爬虫
以加快收录速度。
参数:
urls (list 或 str): 要推送的URL列表例如 ['https://example.com/article/1', 'https://example.com/article/2']
注意:函数期望接收一个列表,但代码中直接使用了 '\n'.join因此传入必须为可迭代的URL列表。
实现逻辑:
1. 将 URL 列表用换行符连接成字符串
2. 向 settings.BAIDU_NOTIFY_URL 指定的百度推送接口发送 POST 请求
3. 记录百度返回的响应结果到日志
4. 捕获并记录任何异常
注意:
- 需在 Django 的 settings 中配置 BAIDU_NOTIFY_URL百度提供的推送接口地址
- 百度推送接口要求每次最多提交2000条URL
"""
try:
data = '\n'.join(urls) # 将多个 URL 用换行符拼接,符合百度推送接口格式要求
result = requests.post(settings.BAIDU_NOTIFY_URL, data=data) # 发送 POST 请求到百度推送接口
logger.info(result.text) # 记录百度服务器返回的响应内容(如成功/失败信息)
except Exception as e:
logger.error(e) # 记录请求过程中发生的任何异常(如网络错误、超时等)
#wwc
@staticmethod
def notify(url):
"""
通用通知接口,当前默认调用百度推送。
参数:
url (list): 要推送的URL列表注意参数名是单数 'url',但实际应传入列表)
注意:
此方法存在命名误导:
- 方法名是 notify参数是 url单数但内部调用 baidu_notify而 baidu_notify 期望接收一个列表
- 因此实际使用时仍需传入列表,例如 notify(['https://example.com/post'])
- 更合理的命名应为 notify_urls 或参数名为 urls
"""
SpiderNotify.baidu_notify(url) # 调用百度推送方法传入URL列表