亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用JS從網頁中刪除評論之間的元素

使用JS從網頁中刪除評論之間的元素

胡說叔叔 2023-06-15 15:36:54
我正在嘗試從此網頁收集數據:https://www.biharjobportal.com/bihar-police-constable-bharti/我設法使用此代碼從網站上刪除了所有 GoogleAds 因為它有一個類名,所以很容易:?var theaders = document.getElementsByClassName('adsbygoogle');for (var i=theaders.length-1; i >=0; i--){? ? theaders[i].parentElement.removeChild(theaders[i]);}但是該網頁有這個沒有 IDS、類名等的元素。(請參見屏幕截圖):我只知道要刪除的元素在這些評論之間:? ? ?<!-- WP QUADS Content Ad Plugin v. 2.0.17? -->? ? **codes to remove (as in the picture)**? ? <!-- WP QUADS Content Ad Plugin v. 2.0.17? -->我嘗試使用 XPATH 刪除所有此類項目,但什么也沒發生,這是我寫的代碼:? ? var badTableEval = document.evaluate (? ? "/html/body/div[1]/div/div[1]/main/article/div/div/ul[3]",? ? document.documentElement,? ? null,? ? XPathResult.FIRST_ORDERED_NODE_TYPE,? ? null);if (badTableEval? &&? badTableEval.singleNodeValue) {? ? var badTable? = badTableEval.singleNodeValue;? ? badTable.parentNode.removeChild (badTable);}如何從網頁中刪除所有這些元素?
查看完整描述

1 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

您可以通過這種方式檢測文檔中的評論(參見代碼片段)?,F在由您來設計一些巧妙的函數來刪除注釋之間的元素。. 好的,您要求它,包括一種刪除相等注釋之間元素的方法。


const root = document.querySelector("body");

const allEls = [...root.childNodes];

const IS_COMMENT = 8;


allEls.forEach((el, i) => {

  if (el.nodeType === IS_COMMENT) {

    // we have a comment. Find the (index of) next equal comment in [allEls]

    // from this point on

    const subset = allEls.slice(i + 1);

    const hasEqualNextComment = subset

      .findIndex(elss =>

        elss.nodeType === IS_COMMENT &&

        elss.textContent.trim() === el.textContent.trim());


    // if an equal comment has been found, remove every element between 

    // the two comment elements

    if (hasEqualNextComment > -1) {

      subset.slice(1, hasEqualNextComment - 1)

        .forEach(elss =>

          elss.parentNode && elss.parentNode.removeChild(elss));

    }

  }

});

body {

  font: normal 12px/15px verdana, arial;

  margin: 2rem;

}

<!-- WP QUADS Content Ad Plugin v. 2.0.17  -->

<ul>

  <li>item 1</li>

  <li>item 2</li>

  <li>item 3</li>

</ul>

<!-- WP QUADS Content Ad Plugin v. 2.0.17  -->


<!-- other comment -->

<ul>

  <li>item 4</li>

  <li>item 5</li>

  <li>item 6</li>

</ul>

<!-- other comment: the above is kept -->


<!-- something 2 remove -->

<div>item 7</div>

<!--something 2 remove-->

<div>item 8</div>


<p>

  <b>The result should show item 4 - item 6, item 8 and the 

    text within this paragraph</b>.

  <br><i>Note</i>: this will only work for top level comments 

  within the given [root] (so, not for comments that nested 

  within elements).

  <br>Also you may have to clean multiline-comments

  from line endings for comparison.

</p>


查看完整回答
反對 回復 2023-06-15
  • 1 回答
  • 0 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號