从大页面中查找并提取html标签

将很长的html页面配置为字符串。如何提取标签及其内容?任何较长的Wikipedia页面都可以说明问题

出于性能原因,不使用诸如cheerio之类的解析器。出于性能原因,也排除了使用任何可解析整个页面的技术。 (就像already existing的答案一样,请先阅读问题,然后再说一遍)。

通过indexOf("<div class='selector'>");

可以轻松找到开始位置

问题出在结束位置。

如何根据开始标签的位置找到结束</div>在哪里?里面还有很多其他的div。

fanxin8798 回答:从大页面中查找并提取html标签

原始javascript报废:(我在finder元素中放入了一些内部SPAN标记。

var htmlString = "<body><h1>Welcome</h1><div class='wrapper'><div>Some content here<div class='selector'>This is the element <span>you <title>want</title> to </span>extract</div></div></div></body>";

var finder = "<div class='selector'>";
var AhtmlString = htmlString.split(finder);

var back = AhtmlString[1].split("</");
var countInside = back[0].split("<"); // count how many internal tags there are
var backClose = back[countInside.length].split(">")[0]; // get the closing tag name (it'll be the first one of the last one we counted

console.log(finder + back.slice(0,countInside.length).join("</") + "</" + backClose + ">");
,

如果我对您的理解正确,那么您实际上只有一个HTML字符串,而不是解析了该HTML的实际页面。

您可以轻松地解决该问题,方法是使用该HTML字符串加载一个临时元素(但实际上不将其包含在DOM中),然后使用DOM API而不是string方法来提取所需的部分。

这是一个按比例缩小的示例:

let htmlString = "<body><h1>Welcome</h1><div class='wrapper'><div>Some content here<div class='selector'>This is the element you want to extract</div></div></div></body>";

// Load the html string up into a temporary object that isn't part of the DOM
let temp = document.createElement("div");
temp.innerHTML = htmlString;

// Now use the DOM API to extract what you need:
let part = temp.querySelector("div.selector");

// Use outerHTML to get the tag iteself along with its contents
console.log(part.outerHTML);

,

这在3毫秒内效果很好,而不是使用250毫秒的解析器。 确实不需要解析所有文档。

const findTag = (body,tagStart,tagName) => {
  const startIndex = body.indexOf(tagStart)
  if (startIndex === -1) return

  const endIndex = findEndIndex(body,startIndex,tagName)
  return body.substring(startIndex,endIndex)
}

const findEndIndex = (body,tagName) => {
  const starting = `<${tagName}`
  const closing = `</${tagName}`

  let index = startIndex + 1
  let level = 1

  do {
    const nextStartPosition = body.indexOf(starting,index)
    const nextClosingPosition = body.indexOf(closing,index)
    level += nextClosingPosition < nextStartPosition ? -1 : 1
    index = Math.min(nextClosingPosition,nextStartPosition) + 1
  } while (level !== 0)

  return index + 2 + tagName.length//to include end tag in substr
}
本文链接:https://www.f2er.com/3092368.html

大家都在问