在不断增加的 URL 中搜索文本

Search Increasing URL For Text

本文关键字:搜索 文本 URL 不断增加      更新时间:2023-09-26

对于 stekhn,这里有正确的链接:var location = "http://www.roblox.com/Trade/inventoryhandler.ashx?filter=0&userid=" + i + "&page=1&itemsPerPage=14";

我正在尝试创建一个 Javascript 脚本,我可以在其中搜索用户清单,检测他们的清单中是否有我正在寻找的东西,并输出用户 ID(如果他们有(。

如果我输入 bluesteel,我需要一个 Javascript 脚本,它将搜索 http://snackyrite.com/site.ashx?userid=1 并检测它上面是否有文本"bluesteel"——如果是,我需要它来显示用户 ID,即 1。

您可能认为这很容易,我可以轻松找到脚本 - 嗯,有一个问题,我的目标不仅是让它搜索 userid=1,我需要它从 userid=1 搜索到 userid=45356

如果在 userid=5、userid=3054 和

userid=12 上找到单词"bluesteel"(这些只是示例(,我需要它在运行脚本的同一页面上显示 5、3054 和 12(ID(。

这是我尝试过的脚本,但用户 id 不会增加(我不确定该怎么做(。

var location = http://snackyrite.com/site.ashx?userid=1;
if(location.indexOf("bluesteel") > -1) {
    output.userid
}

我很抱歉,Javascript不是我最好的。

使用循环:

for (var i = 1; i <=45356; i++) {
    var loc = "http://snackyrite.com/site.ashx?userid="+i;
    // get contents of location
    if (contents.indexOf("bluesteel") > -1) {
        console.log(i);
    }
}

由于获取内容可能会使用 AJAX,因此if可能会在回调函数中。看到Javascript臭名昭著的循环问题吗?了解如何编写循环,以便i保留在回调函数中。

这种网页抓取无法在浏览器(客户端JavaScript(中完成。

我建议使用 Node.js 构建一个刮板。

  1. 安装节点.js
  2. 安装请求npm i request
  3. 安装 cheerio npm i cheerio
  4. 创建文件scraper.js
  5. 运行node scraper.js

scraper.js代码

// Import the scraping libraries
var request = require("request");
var cheerio = require("cheerio");
// Array for the user IDs which match the query
var matches = [];
// Do this for all possible users
for (var i = 1; i <= 45356; i++) {
    var location = "http://snackyrite.com/site.ashx?userid="+i;
    request(location, function (error, response, body) {
        if (!error) {
            // Load the website content
            var $ = cheerio.load(body);
            var bodyText = $("body").text();
            // Search the website content for bluesteel
            if (bodyText.indexOf("bluesteel") > -1) {
                console.log("Found bluesteel in inventory of user ", i);
                // Save the user ID, if bluesteel was found
                matches.push(i);
            }
        // Something goes wrong
        } else {
            console.log(error.message);
        }
    });
    console.log("All users with bluesteel in inventory: ", matches);
}

上面的代码似乎有点复杂,但我认为这是应该完成的方式。当然,您可以使用任何其他抓取工具,库。