[英]How can I use javscript to search for html tags on the response of a get request?
I have a get request that returns a whole HTML page and I want to get a specific information from that page that is under one of the many 'td' tags. 我有一个获取请求,返回一个完整的HTML页面,我想从该页面获取一个特定信息,该信息位于众多'td'标签之一。 The tags are simple and dont have any classes or ids.
标签很简单,没有任何类或ID。
axios.get("https://example.com")
.then(res =>{
console.log(res.data.body) // returns an empty array
console.log(res.data) // returns the whole html page
//Here I tried somehow to pass the html page to the document
//so i could try use jquery or javascript to find the tags
//This does not work
document = res.data
var test = document.getElementsByTagName("td")
//Here I wanted to loop through the document to find the information
for(let index = 0; index < res.data.length; index++)
{
console.log(res.data[index])
//this outputs each character of the html page
if(res.data[index].innerHTML == "label")
{
console.log(res.data[index+1])
}
}
})
I want to find a TD tag with a specific innerHTML. 我想找到一个带有特定innerHTML的TD标签。 That works like a label and it is always the same.
这就像一个标签,它总是一样的。 I would then use something like res.data[index+1] to get the next tag and pull out the innerHTML.
然后我会使用res.data [index + 1]之类的东西来获取下一个标签并取出innerHTML。
Is there a way I can do this? 有没有办法可以做到这一点?
How can I use javascript to search for html tags on the response of a get request? 如何使用javascript在get请求的响应中搜索html标签?
That response is from a third part API. 该响应来自第三方API。
Edit : this might not work on any kind of HTML string. 编辑 :这可能不适用于任何类型的HTML字符串。 Since you mention a "whole page", it might depend on how clean it is DOM-wise.
既然你提到了一个“整页”,它可能取决于它是多么干净的DOM。
Edit 2 (related to the above): if that does not work, you can try this instead: 编辑2 (与上述相关):如果不起作用,您可以尝试这样做:
let $matchingRows = $('<div>').append($.parseHTML(html))
.find('td')
// ...
(Source: https://stackoverflow.com/a/30677065/965834 and related questions.) (来源: https : //stackoverflow.com/a/30677065/965834及相关问题。)
Original answer: 原始答案:
Since you mention jQuery, you can use $(yourHtmlString)
to get a selector from it: 既然你提到了jQuery,你可以使用
$(yourHtmlString)
从中获取一个选择器:
let html = ` <table> <tr> <td>foo</td> <td>label</td> <td>bar</td> <td>label</td> </tr> </table>`; let $matchingRows = $(html) .find('td') .filter((_, e) => $(e).html() === 'label'); console.log($matchingRows.length);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can create an element and fill the returned html into that so you have an variable/element you can run queries on. 您可以创建一个元素并将返回的html填充到该元素中,这样您就可以运行查询的变量/元素。
something like this 这样的事情
axios.get("https://example.com")
.then(res => {
const doc = document.createElement("div");
doc.innerHTML = res.data;
console.log( doc.querySelectorAll("td") );
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.