简体   繁体   English

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

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

I'm making a Discord bot in JavaScript and implementing a feature where when you ask a coding question it gives you a snippet.我正在 JavaScript 中制作 Discord 机器人并实现一个功能,当您询问编码问题时,它会为您提供一个片段。 I'm using Grepper and returning the url with the search results.我正在使用Grepper并返回 url 和搜索结果。 For example: Hello World in JavaScript Search Results .例如: JavaScript 搜索结果中的 Hello World I would like to access the div containing the snippet.我想访问包含片段的 div。 Is this possible?这可能吗? And how would I do it?我该怎么做?

Here's my code:这是我的代码:

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:

}

I'm new to JavaScript so sorry if this is a stupid question.我是 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. 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. If you need more information you can check this Unofficial List of Grepper APIs如果您需要更多信息,可以查看非官方 Grepper API 列表

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

How Do I Access the div containing the snippet?如何访问包含片段的 div?
To access the div you might need to use python web scraping to scrape the innerHTML of the div but I think it's easier to use the other API.要访问 div,您可能需要使用 python web 抓取来抓取div 的innerHTML ,但我认为使用其他 API 更容易。

Or或者

You can put /api/ in the url like:您可以将/api/放入 url 中,例如:

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

The best way is to use the grepper api.最好的方法是使用 grepper api。

Install node-fetch安装节点获取

npm i node-fetch , You need this package for making requestes to the api. npm i node-fetch ,您需要这个 package 来向 api 发出请求。 To import It in the code just type:要在代码中导入它,只需键入:

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

Write this code写下这段代码

Modify your code like this:像这样修改你的代码:

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);
    });
        
}

这是输出

The easiest way for this is to send a GET request to the underlying API最简单的方法是向底层 API 发送 GET 请求

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

This will return the answers in JSON format.这将以 JSON 格式返回答案。 Obviously you'd have to adjust the parameters.显然你必须调整参数。

How did I find out about this?我是怎么知道的?
Simply look at the network tab of your browser's dev tools while loading the page.只需在加载页面时查看浏览器开发工具的网络选项卡。 You'll see a GET request being sent out to the endpoint, returning mentioned answers as JSON.您将看到一个 GET 请求被发送到端点,返回提到的答案为 JSON。

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

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