将内部文本获取到lastchild元素之前

时间:2019-03-20 06:07:39

标签: javascript node.js puppeteer

我有以下示例,其中我尝试提取“ a”元素的内部文本,该元素是位于列表最后一个子元素之前的“ i”元素的子元素。

示例:

<div class="lms-pagination" id="lms-pagination">    
	<ul>      
        <li class="disabled">
          <span class="current prev">Previous page</span>
        </li>
        <li class="active">
          <span class="current en-lang">1</span>
        </li>        
        <li>
          <a data-page="1" class="page-link en-lang">2</a>
        </li>
        <li>
          <a data-page="2" class="page-link en-lang">3</a>
        </li>
        <li class="disabled"><span class="ellipse">...</span></li>
        <li>
          <a data-page="17" class="en-lang">18</a> <!-- Try to extract 18 in this example -->
        </li>
        <li>
          <a href="#1" class="next">Next page</a>
        </li>
  </ul>
</div>

我正尝试使用

                    lastPage = await newPage.$$eval('#lms-pagination>ul>li:nth-child(???)>a', el => el.innerText);

2 个答案:

答案 0 :(得分:1)

使用Javascript:=

function myFunction() {
  var list = document.getElementById("myList").lastChild.innerHTML;
  document.getElementById("demo").innerHTML = list;

  var items = document.querySelectorAll("li");
  var lastchild = items[items.length - 2].innerHTML;
  document.getElementById("demo1").innerHTML = lastchild;
}
<p>Example list:</p>
<ul id="myList">
  <li>Coffee</li>
  <li>Tea</li>
  <li>Coffee22</li>
  <li>Tea22</li>
  <li>Coffee33</li>
  <li>Tea33</li>
</ul>
<p>Click the button to get the HTML content of the list's last child node.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
</script>

使用jQuery:=

alert($("li:nth-last-of-type(2)").text())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="lms-pagination" id="lms-pagination">
  <ul>
    <li class="disabled">
      <span class="current prev">Previous page</span>
    </li>
    <li class="active">
      <span class="current en-lang">1</span>
    </li>
    <li>
      <a data-page="1" class="page-link en-lang">2</a>
    </li>
    <li>
      <a data-page="2" class="page-link en-lang">3</a>
    </li>
    <li class="disabled"><span class="ellipse">...</span></li>
    <li>
      <a data-page="17" class="en-lang">18</a>
      <!-- Try to extract 18 in this example -->
    </li>
    <li>
      <a href="#1" class="next">Next page</a>
    </li>
  </ul>
</div>

答案 1 :(得分:0)

您可以像这样获得倒数第二个孩子的值。 $("li").eq(-2).text()