簡體   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