首页 > 解决方案 > 遍历html文件获取aa href

问题描述

我的html文件如下

<div id="sidebar" style="top: 100px;">
    <div class="items">
        <div class="item hentry selected" itemscope="" itemtype="http://schema.org/BlogPosting" data-id="3714235398193725034">

            <img class="thumbnail" src="http://4.bp.blogspot.com/-FLnjwm6youQ/UUGhQei8KqI/AAAAAAAAAUE/nEl-5V5IcDw/s30-p/1.jpg" style="width: 30px; height: 30px;">

            <h3 class="title entry-title" itemprop="name">


    <a href="http://mywebsiteurl/2013/03/blog-post.html" rel="bookmark" itemprop="url">art1</a>

  </h3>

        </div>
        <div class="item hentry" itemscope="" itemtype="http://schema.org/BlogPosting" data-id="179325489509322215">
.
.
.
      </div>
  </div>
</div>

html 有一个带有 id 侧边栏的 div

在此之下,还有另一个带有类项目的 div

在此之下有多个带有类项目的div

在每个带有类项目的 div 下,我有一个带有类标题的 h3

在 h3 标签下我有 'a' 标签

我需要在所有具有类项的 div 下获取“a”标签的 href 值。

对于如何做同样的事情,我将不胜感激。

谢谢

标签: javascripthtmlnode.jscheerio

解决方案


一旦尝试使用内联 jQuery:

$.each($("#sidebar .items .item h3 a"),function(a,b){console.log($(b).attr("href"));});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sidebar" style="top: 100px;">
    <div class="items">
        <div class="item hentry selected" itemscope="" itemtype="http://schema.org/BlogPosting" data-id="3714235398193725034">

            <img class="thumbnail" src="http://4.bp.blogspot.com/-FLnjwm6youQ/UUGhQei8KqI/AAAAAAAAAUE/nEl-5V5IcDw/s30-p/1.jpg" style="width: 30px; height: 30px;">

            <h3 class="title entry-title" itemprop="name">


    <a href="http://mywebsiteurl/2013/03/blog-post.html" rel="bookmark" itemprop="url">art1</a>

  </h3>

        </div>
        <div class="item hentry" itemscope="" itemtype="http://schema.org/BlogPosting" data-id="179325489509322215">
           <img class="thumbnail" src="http://4.bp.blogspot.com/-FLnjwm6youQ/UUGhQei8KqI/AAAAAAAAAUE/nEl-5V5IcDw/s30-p/1.jpg" style="width: 30px; height: 30px;">

            <h3 class="title entry-title" itemprop="name">


    <a href="http://example.com" rel="bookmark" itemprop="url">art2</a>

  </h3>
      </div>
  </div>
</div>


推荐阅读