基于python requests模块的sitemap(网站地图)api提交工具,适用于百度站长后台

功能描述

百度站长后台的普通收录的方式有3种,分别是API提交、sitemap地址还有手动添加,其中sitemap的响应时间有时候会比较长,使用API推送是更理想的一种方式。本代码使用的前提是网站已经有支持百度sitemap格式的xml文件页面,首先使用requests.get()方法抓取文件内容,用正则提取出url并转化成字符串之后,通过requests.post()方法向推送接口发送POST请求。

百度sitemap的标准格式
image

百度站长后台的推送接口
image

代码

requests属于第三方库,没有安装的话在terminal使用pip install requests命令安装,这里不做赘述。

类构造函数中的headers的字典,在百度站长平台的后台有相关示例,不确定每个人都一样
image

import re
import requests

class api_send:

    def __init__(self):
        # 此处填写要提交的sitemap的url
        self.web_url = "https://yourdomain/sitemap.xml"
        # 此处填写百度的推送接口
        self.api = "http://data.zz.baidu.com/urls?site=https://yourdomain&token=yourtoken"
        # 此处复制百度的推送示例
        self.headers = {
            'User-Agent': 'curl/7.12.1',
            'Host': 'data.zz.baidu.com',
            'Content - Type': 'text / plain',
            'Content - Length': '83'
        }
        # 这里填写正则表达式的规则,如果是其他形式的sitemap,是需要做调整的
        self.url_reg = re.compile("<loc>(.*)</loc>")

    def web_request(self):
        headers = {
           "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36 Edg/90.0.818.42"
        }
        self.content = requests.get(url=self.web_url,headers=headers).text

    def get_urls(self):
        li_urls = re.findall(self.url_reg, self.content)
        self.urls = ""
        for url in li_urls:
            self.urls += "\n"+url

    def send_post(self):
        response = requests.post(
            self.api,
            headers = self.headers,
            data = self.urls,
            timeout = 20
        ).text
        return response


if __name__ == '__main__':
    obj = api_send()
    obj.web_request()
    obj.get_urls()
    result = obj.send_post()
    print(result)

运行结果

正常情况下,代码会打印一个字典作为结果,如:{"remain":98904,"success":1096},这样就表示代码运行成功了

posted @ 2021-04-22 10:25  左舷弹幕薄  阅读(397)  评论(0编辑  收藏  举报