百度主动推送python解决方案

题记:

今天搞网站的百度链接提交的时候,发现sitemap处于等待状态已经有一个星期了,手动提交实在太麻烦了,没办法只能搞主动推送了。本以为很简单的事情但是搞了很久,,,我用的Requests以POST方法推送,其他方法暂不介绍。

分别有以下几种接口API文档地址

推送链接

 POST /urls?site=https://www.lyonghu.com&token=* HTTP/1.1
User-Agent: curl/7.12.1 
Host: data.zz.baidu.com 
Content-Type: text/plain 
Content-Length: 83 

http://www.lyonghu.com/1.html
http://www.lyonghu.com/2.html

更新数据

 POST /update?site=https://www.lyonghu.com&token=* HTTP/1.1
User-Agent: curl/7.12.1 
Host: data.zz.baidu.com 
Content-Type: text/plain 
Content-Length: 83 


http://www.lyonghu.com/1.html
http://www.lyonghu.com/2.html

删除数据

POST /del?site=https://www.lyonghu.com&token=* HTTP/1.1
User-Agent: curl/7.12.1 
Host: data.zz.baidu.com 
Content-Type: text/plain 
Content-Length: 83 


http://www.lyonghu.com/1.html
http://www.lyonghu.com/2.html

分析

API文档中并没有介绍说POST的body中应该以怎样的数据结构传输,只是有一个请求头的设定 Content-Type: text/plain,想着应该是文本或者字符的模式传输了。

三种API接口,大同小异,本文只以推送接口为例进行开发;

代码

首先引入Requests库,

import requests

两种解决方法

以字节流传值


filePath = "./sitemap/"

headers = {
    "usr-agent": "curl/7.12.1",
    "host": "data.zz.baidu.com",
    "content-type": "text/plain"
}

url = "http://data.zz.baidu.com/urls?site=https://www.lyonghu.com&token=*"

textFile = open(filePath + "u8site.txt", "r")
textFileValue = textFile.read().encode(encoding="UTF-8")
print(type(textFileValue))
textFile.close()
response = requests.post(url,data=textFileValue,timeout=30)

if(response.status_code == 200):
    # pass
    print("success = " + str(response.json()["success"]))

为什么是字节流:

Convert a mapping object or a sequence of two-element tuples, which may contain str or bytes objects, to a percent-encoded ASCII text string. If the resultant string is to be used as a data for POST operation with the urlopen() function, then it should be encoded to bytes, otherwise it would result in a TypeError.

以二进制流传值

filePath = "./sitemap/"

headers = {
    "usr-agent": "curl/7.12.1",
    "host": "data.zz.baidu.com",
    "content-type": "text/plain"
}

url = "http://data.zz.baidu.com/urls?site=https://www.lyonghu.com&token=*"

textFile = {"file":open(filePath + "u8site.txt", "rb")}
response = requests.post(url,files=textFile,timeout=30)
if(response.status_code == 200):
    # pass
    print("success = " + str(response.json()["success"]))

提示:

以上代码运行在我的sitemap生成的site.text文件基础之上。

本站所有文章除特殊声明外均为原创,未经允许禁止转载!
换个声音
停止播放