从DIV获取IMG链接返回null



我正试图从HTML页面中的div获取IMG地址。当我呼叫时

document.getElementById('m-person--image l-person--image')

它返回NULL。

以下是我尝试执行此操作的HTML页面:https://www.biography.com/business-figure/tim-cook

我试图提取蒂姆·库克的图像地址。有什么想法吗?感谢

在您提供的页面上,m-person--imagel-person--image是包装图像元素的div上的类,而不是id。您可以使用querySelector函数通过类来获取此图像元素:

document.querySelector('.m-person--image.l-person--image > img');

document.getElementsByClassName('m-persons-image'(

这种方式非常适合

document.querySelector('img[alt="Tim Cook"').src

您正试图使用id,但您要查找的div由class标识

<div class="m-person--image l-person--image">
<img src="https://www.biography.com/.image/ar_1:1%2Cc_fill%2Ccs_srgb%2Cg_face%2Cq_auto:good%2Cw_300/MTE5NDg0MDU1MzM0OTc5MDg3/tim-cook-20967297-1-402.jpg" alt="Tim Cook" itemprop="image" nopin="true" data-pin-no-hover="true">
</div>

使用getElementsByClassName

document.getElementsByClassName('m-person--image l-person--image')

最新更新