从存储在数组中的HTML中拉取链接

时间:2018-06-07 12:51:45

标签: javascript html

我试图从以下html中提取链接。 HTML中有很多像这样的HTML。

推文[0]是:



var tweets = Array.from(document.querySelectorAll("[class ^= AdaptiveMedia-ph]"));
console.log(tweets);

<div class="AdaptiveMedia-photoContainer js-adaptive-photo " data-image-url="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" data-element-context="platform_photo_card" style="background-color:rgba(51,64,18,1.0);" data-dominant-color="[51,64,18]">
  <img data-aria-label-part="" src="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" alt="A tree" style="width: 100%; top: -0px;">
</div>
&#13;
&#13;
&#13;

如何实际拉动&#34; src&#34;来自&#34; alt&#34;的alt文本从HTML文本?提前致谢!

2 个答案:

答案 0 :(得分:2)

像这样:

var tweets = document.querySelectorAll("[class ^= AdaptiveMedia-ph]");
for (var i=0;i<tweets.length;i++) {
  console.log("data-image-url",tweets[i].getAttribute("data-image-url"));
  var img = tweets[i].querySelector("img");
  console.log("image-url",img.src,"alt",img.alt);
  
}
<div class="AdaptiveMedia-photoContainer js-adaptive-photo " data-image-url="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" data-element-context="platform_photo_card" style="background-color:rgba(51,64,18,1.0);" data-dominant-color="[51,64,18]">
  <img data-aria-label-part="" src="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" alt="A tree" style="width: 100%; top: -0px;">
</div>

答案 1 :(得分:1)

如果您直接选择.map()元素,然后只选择// Select img inside the cards var tweets = Array.from(document.querySelectorAll("[class ^= AdaptiveMedia-ph] img")); var imgData = tweets.map(e => ({src: e.src, alt: e.alt})); console.log(imgData);结果,会更容易:

<div class="AdaptiveMedia-photoContainer js-adaptive-photo " data-image-url="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" data-element-context="platform_photo_card" style="background-color:rgba(51,64,18,1.0);" data-dominant-color="[51,64,18]">
  <img data-aria-label-part="" src="https://pbs.twimg.com/media/DfFmgY6WAAAh0sG.jpg" alt="A tree" style="width: 100%; top: -0px;">
</div>
    SELECT 
        ID, 
        User,
        Hour,
        Minute
    FROM table 
    WHERE MOD( Minute, 3 ) = 0
    ORDER BY Hour ASC, Minute ASC;