【问题标题】:How can I extract the link to the image here?如何在此处提取图像的链接?
【发布时间】:2021-10-09 05:22:27
【问题描述】:

我正在使用 BS4 抓取网页中的文章标题、作者姓名以及指向其封面图片的链接。

这是我为特定文章的图片找到的 HTML 标记:

<img src="https://cdn.theatlantic.com/thumbor/lYaNkJfiPr8_Jp5Pj5ikj94GJgQ=/183x0:2000x1125/210x130/media/img/2021/06/WEL_Tiffany_KodakOpenerAlt-1/original.jpg" alt="Photo collage on a yellow background" loading="lazy" class="Image_root__J8Wlz Image_lazy__1w_jB Image_loaded__3uNg2 LandingRiver_image__1ZCUb" width="210" height="130" srcset="https://cdn.theatlantic.com/thumbor/lYaNkJfiPr8_Jp5Pj5ikj94GJgQ=/183x0:2000x1125/210x130/media/img/2021/06/WEL_Tiffany_KodakOpenerAlt-1/original.jpg, https://cdn.theatlantic.com/thumbor/NL-ZZp6sHiX_1WX2bn9f9o1WWjk=/183x0:2000x1125/420x260/media/img/2021/06/WEL_Tiffany_KodakOpenerAlt-1/original.jpg 2x">

这是我用来获取图片 URL 的代码:

cover_image = card.find('img')['src']

但是,而不是

"https://cdn.theatlantic.com/thumbor/lYaNkJfiPr8_Jp5Pj5ikj94GJgQ=/183x0:2000x1125/210x130/media/img/2021/06/WEL_Tiffany_KodakOpenerAlt-1/original.jpg"

它不断返回

data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 210 130' /%3E

我也尝试过获取标记的“srcset”部分,但它甚至没有出现在代码中。

在这种情况下我该怎么办?

【问题讨论】:

  • 一个html中有多个img标签,find给你第一个匹配,试试class_="Image_root__J8Wlz Image_lazy__1w_jB Image_loaded__3uNg2 LandingRiver_image__1ZCUb"

标签: python html image web-scraping beautifulsoup


【解决方案1】:

尝试使用Epis95 建议的类名进行选择:

cover_image = card.find('img',class_ = "Image_root__J8Wlz Image_lazy__1w_jB Image_loaded__3uNg2 LandingRiver_image__1ZCUb")['src']

# and if you want the best image quality you could do

# firstly get the srcset
cover_image = card.find('img',class_ = "Image_root__J8Wlz Image_lazy__1w_jB Image_loaded__3uNg2 LandingRiver_image__1ZCUb")['srcset']

# as srcset is a string but the links are seperated using ',' you could split it on the same
cover_image = cover_image.split(',')

# after splitting the best image quality lik is the last one so get the last element of the new list that you have after splitting
cover_image = cover_image[-1]

# you now have a string with 2x as the unwanted part at the last and you could remove that using the slice operation
cover_image = cover_image[:-2]    # slice it upto the third last characterto chop off '2x'

# now you have a string with leading and trailing spaces so strip it to remove any leading or trailing spaces
cover_image = cover_image.strip()
print(cover_image)    # this is the best quality image you can get
输出:
https://cdn.theatlantic.com/thumbor/NL-ZZp6sHiX_1WX2bn9f9o1WWjk=/183x0:2000x1125/420x260/media/img/2021/06/WEL_Tiffany_KodakOpenerAlt-1/original.jpg

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-30
    • 2019-12-30
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多