百度链接提交-主动推送Python版

一、现状

百度目前提供自动提交链接和手动提交链接两种方式,其中自动提交又分为主动推送、自动推送和sitemap三种形式,按百度的说法,主动推送的效果最好,百度站长平台后台也提供了curl、php、ruby的推送示例代码但没有提供python代码,网上很少有现成的python版本主动推送代码(仅有的也有点小问题,需要修改一下),现将目前我正在使用的主动推送python代码贴出。

二、站点地图

1、插件生成

参考这篇文章:WordPress网站地图插件SiteMAP

生成网站地图链接(以本站为例):https://www.katexiaohao.xyz/sitemap.xml

2、代码生成

代码下载:

来源:默认网盘

代码位置:

将下载文件解压后放在WordPress项目的根目录,位置如图:

图片.jpg

生成网站地图链接(以本站为例):https://www.katexiaohao.xyz/sitemap.php

三、主动推送

self._send_url:

图片.jpg

site:你的网站地址

token:提交接口准入签名

import requests
from xml.etree import ElementTree


class SEO(object):
    def __init__(self):
        self._urls = ''
        self._blog_sitemap_url = '{Your HostName}/sitemap.xml'
        # self._blog_sitemap_url = '{Your HostName}/sitemap.php'
        self._send_url = 'http://data.zz.baidu.com/urls?site={Your HostName}&token=TOKEN'

    # 读取sitemap.xml文件
    def get_sitemap_xml(self):
        response = requests.get(self._blog_sitemap_url)
        return response.text

    # 解析xml文件
    def parse_xml(self):
        root = ElementTree.fromstring(self.get_sitemap_xml())
        for item in root:
            for i in item:
                if 'loc' in i.tag and '{Your HostName}/' in i.text:
                    self._urls += i.text + '\n'

    # 推送到百度
    def send_baidu(self):
        self.parse_xml()
        headers = {
            'User-Agent': 'curl/7.12.1',
            'Host': 'data.zz.baidu.com',
            'Content-Type': 'text/plain',
            'Content-Length': '83',
            'charset': 'gbk'
        }
        response = requests.post(url=self._send_url, data=self._urls, headers=headers)
        print(response.status_code, response.text)

if __name__ == '__main__':
    SEO().send_baidu()

如果想要做定时推送,可以参考Python使用APScheduler实现定时任务 或者 利用crontab定时执行任务及配置方法

百度链接推送规则见传送

四、写在最后

入门使用就这些,更高深的用法在实践中去发现吧。。。

 

THE END
分享
二维码
打赏
< <上一篇
下一篇>>