繁体   English   中英

我可以使用 JavaScript 从 web 页面访问元素吗?

[英]Can I access elements from a web page with JavaScript?

我正在 JavaScript 中制作 Discord 机器人并实现一个功能,当您询问编码问题时,它会为您提供一个片段。 我正在使用Grepper并返回 url 和搜索结果。 例如: JavaScript 搜索结果中的 Hello World 我想访问包含片段的 div。 这可能吗? 我该怎么做?

这是我的代码:

if (message.startsWith('programming')) {
    // Command = programming
    message = message.replace('programming ', ''); // Remove programming from the string
    message = encodeURIComponent(message) // Encode the string for a url
    msg.channel.send(`https://www.codegrepper.com/search.php?answer_removed=1&q=${message}`); // Place formatted string into url and send it to the discord server
    
    // Here the program should access the element containing the snippet instead of sending the url:

}

我是 JavaScript 的新手,如果这是一个愚蠢的问题,我很抱歉。

As far as I know the API you are using returns HTML/Text data, not JSON, Grepper has a lot more APIs if you just look into them, you can instead use this API that returns JSON data. 如果您需要更多信息,可以查看非官方 Grepper API 列表

https://www.codegrepper.com/api/get_answers_1.php?v=2&s=${SearchQuery}&u=98467

如何访问包含片段的 div?
要访问 div,您可能需要使用 python web 抓取来抓取div 的innerHTML ,但我认为使用其他 API 更容易。

或者

您可以将/api/放入 url 中,例如:

https://www.codegrepper.com/api/search.php?answer_removed=1&q=js%20loop

最好的方法是使用 grepper api。

安装节点获取

npm i node-fetch ,您需要这个 package 来向 api 发出请求。 要在代码中导入它,只需键入:

const fetch = require('node-fetch');

写下这段代码

像这样修改你的代码:

if (message.startsWith('programming')) {
    message = message.replace('programming ', '');
    message = encodeURIComponent(message)
    
    // Making the request
    fetch(`https://www.codegrepper.com/api/search.php?answer_removed=1&q=${message}`)
    .then(res => res.json())
    .then(response => {
        // response is a json object containing all the data You need
        // now You need to parse this data
        const answers = response.answers; // this is an array of objects
        const answers_limit = 3; // set a limit for the answers
        
        // cheking if there is any answer
        if(answers.length == 0) {
            return msg.channel.send("No answers were found!");
        }

        // creating the embed
        const embed = new Discord.MessageEmbed()
            .setTitle("Here the answers to your question!")
            .setDescription("")
        
        // parsing
        for(let i = 0; i < answers_limit; i++) {
            if(answers[i]) {
                embed.description += `**${i+1}° answer**:\n\`\`\`js\n${answers[i].answer}\`\`\`\n`;
            }
        }
        console.log(embed)

        msg.channel.send(embed);
    });
        
}

这是输出

最简单的方法是向底层 API 发送 GET 请求

https://www.codegrepper.com/api/search.php?q=hello%20world%20javascript&search_options=search_titles

这将以 JSON 格式返回答案。 显然你必须调整参数。

我是怎么知道的?
只需在加载页面时查看浏览器开发工具的网络选项卡。 您将看到一个 GET 请求被发送到端点,返回提到的答案为 JSON。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM