我正在从“纽约时报”的网站上抓取元数据。我想收集三条信息:
除了NYTimes主页在主页上显示文章的图片外,我成功地收集了这三篇文章。在这种情况下,我试图捕捉到主页缩略图,但没有成功。到目前为止,我的代码如下:
for item in soup.select('.story-wrapper'):
try:
headline = item.find('h3').get_text()
link = item.find('a')['href']
image = item.select('.css-hdqqnp')css选择器.css-hdqqnp引用显示在NYTimes主页上的文章图像的缩略图图像类(而不仅仅是文本)。
如果文章的缩略图已经显示在主页上,而不是只显示在文章页面(我已经成功地收集到),那么如何获得它的缩略图呢?
发布于 2021-06-12 07:03:35
问题是HTML结构是
<div class="..." span="4">
<div class="....">
<section class="story-wrapper"> ... </section>
</div>
</div>
<div class="..." span="6">
<div class="....">
<!-- ... your nested img-tag inside a div-tag with css class 'css-hdqqnp' -->
</div>
</div>也就是说,图像不在区段标签内.相反,它位于节的祖父母标记的下一个兄弟标记中。因此,您可以搜索这样的图像缩略图:
for item in soup.select('.story-wrapper'):
headline = item.find('h3').get_text()
link = item.find('a')['href']
if (sibling := item.parent.parent.next_sibling) is not None:
if (image := sibling.find("img")) is not None:
image_url = image["src"]https://stackoverflow.com/questions/67945766
复制相似问题