1. 程式人生 > 實用技巧 >必應API介面nodejs版

必應API介面nodejs版

近期,在研究百度、必應、API等的url提交API時,發現有用Go語言做工具的大佬的分享 利用 API 自動向搜尋引擎提交網址(Go語言版) - pyList

其中提到bing API提交方法,並給出了Go語言程式碼:

func Bing() {
    sUrl := "https://ssl.bing.com/webmaster/api.svc/json/SubmitUrl?apikey=xxxxxxxx"
    buf := bytes.NewBufferString(`{
"siteUrl":"https://pylist.com",
"url":"https://pylist.com/t/1581940902"
}`)
    req, err := http.NewRequest("POST", sUrl, buf)
    if err != nil {
        return
    }
    req.Header.Set("Content-Type", "application/json; charset=utf-8")

    resp, err := http.DefaultClient.Do(req)
    if err != nil {
        return
    }
    defer resp.Body.Close()
}

可以儲存為: bing-push.go, 然後在本地執行哈~

而相比於go語言,我本人對node.js更熟悉一點~

必應API介面-單條提交

var request = require('request');
var options = {
    uri: 'https://ssl.bing.com/webmaster/api.svc/json/SubmitUrl?apikey=' + 'xxx', /* xxx需替換為你的key */
    method: 'POST',
    json: {
        "siteUrl": "http://geekplayers.com", /* 替換為你的站點,並且在Bing站長平臺中驗證過許可權 */
        "url": "http://geekplayers.com/link.html"   /* 替換為你需要推送的url */
    }
};

request(options, function (error, response, body) {
    console.log("Bing response: ", body)
});

登入必應站長後臺https://www.bing.com/webmasters,點右上角的設定按鈕(齒輪⚙),找到你的key:

Step 1:

Step 2:

然後將上述程式碼中的xxx替換為你的key。

先儲存檔案為: bing-SingleSumbit.js,

然後在當前目錄下開啟命令列,輸入 npm install request,

接下來改好key, siteurl, url等值後,就可以在命令列中執行:

node bing-SingleSumbit.js

必應API介面-批量提交

批量提交 - 版本1

var request = require('request');
var myJson = {
    "siteUrl": "http://geekplayers.com",
    "urlList": [
        "http://geekplayers.com/link.html",
        "http://geekplayers.com/about.html",
        "http://geekplayers.com/blog/"
    ]
};
request({
    url: 'https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=' + 'xxx', /* xxx需替換為你的key */
    method: "POST",
    json: true,   // <--Very important!!!
    body: myJson
}, function (error, response, body) {
    console.log(body);
});

我記得這裡有個跨域的問題, 設定 json: true 即可解決。

先將程式碼儲存為: bing-BatchSumbit.js.

執行方法,同上~

批量提交 - 改進1

在上一版本的基礎上可以改進,即:把多條url先按行放進link.txt中,然後讀取處理~

var fs = require('fs');
var readline = require('readline');
var path = require('path')

function readFileToArr(fReadName, callback) {
    var arr = [];
    var readObj = readline.createInterface({
        input: fs.createReadStream(fReadName)
    });

    readObj.on('line', function (line) {
        arr.push(line);
    });
    readObj.on('close', function () {
        console.log('readLine close....');
        callback(arr);
    });
}

// var urlsFile = path.resolve(__dirname, 'links.txt').replace(/\\/g, '/');  // For Windows
var urlsFile = path.resolve(__dirname, '..', 'nodejs', 'links.txt'); /* 相容 Windows/Linux, 這裡nodejs為上級資料夾名 */

readFileToArr(urlsFile, function (arr) {
    var request = require('request');
    var myJson = {
        "siteUrl": "http://geekplayers.com",
        "urlList": arr
    };
    
    request({
        url: 'https://ssl.bing.com/webmaster/api.svc/json/SubmitUrlbatch?apikey=' + 'xxx',
        method: "POST",
        json: true,   // <--Very important!!!
        body: myJson
    }, function (error, response, body) {
        console.log(body);
    });
});

儲存檔案為: bing-BatchSumbit2.js

命令列中用cd命令切換到當前目錄,然後依次輸入:

npm install fs
npm install readline
npm install path

改好key, siteurl, url等值後,並在當前目錄建立檔案links.txt並填入需要推送的多條url,就可以在命令列中執行:

node bing-BatchSumbit2.js

批量提交 - 改進2

上一版本的程式碼中,links.txt的內容是手動新增的,那我們可不可以從sitemap.xml獲取並直接轉換為.txt供後面使用呢?當然可以,於是另外寫了一段node.js程式碼做這個事。

var fs = require('fs');
var request = require('request');
const cheerio = require('cheerio');

request('https://www.geekplayers.com/sitemap.xml', function (error, response, html) {
    if (!error && response.statusCode == 200) {
        var $ = cheerio.load(html, {
            xmlMode: true
        });

        textFile = 'myLink.txt';
        fs.open(textFile, 'wx', (err, fd) => {
            if (err) {
                if (err.code === 'EEXIST') {
                    console.error('myfile already exists');
                    
                    fs.unlinkSync(textFile);  // Remove file
                }
            }

        });

        const nodes = $('loc');
        var arr = [];
        
        for (i = 0; i < nodes.length; i++) {
            arr[i] = nodes[i].firstChild.data;

            fs.appendFile(textFile, arr[i] + '\r\n', function (err) {
                if (err) {
                    console.error('One line converted failed.'); // append failed
                } else {
                    // console.error('One line converted done!');
                }                
            })
        }

        console.error('Converted done!');
    }
});

// Reference: https://stackoverflow.com/a/25012834/6075331

先儲存程式碼為: sitemapInXMLtoText.js,

命令列中用cd命令切換到當前目錄,然後依次輸入:

npm install fs
npm install request
npm install cheerio

改好key, siteurl, url等值後,就可以在命令列中執行:

node sitemapInXMLtoText.js

接下來只需將request呼叫時的第一個引數改為你的sitemap.xml的網址即可~

最後再到命令列中執行一次:

node bing-BatchSumbit2.js

Bing還提供了其他API介面

GetKeywordStats - Bing

https://ssl.bing.com/webmaster/api.svc/json/GetKeywordStats?q=dog%20beds&country=be&language=nl-BE&apikey=...

RSS Feed提交:

https://bing.com/webmaster/api.svc/json/SubmitFeed

獲取使用者驗證後的站點資訊:

https://ssl.bing.com/webmaster/api.svc/json/GetUserSites

有興趣的朋友可以繼續深入研究哈, 歡迎在評論區留言交流~

作 者: 極客玩家大白
首發於: 必應API介面nodejs版 - 極客玩家大白