【问题标题】:Can't extract src attribute from "img" tag with BeautifulSoup无法使用 BeautifulSoup 从“img”标签中提取 src 属性
【发布时间】:2021-07-27 07:24:21
【问题描述】:

我正在处理一个项目,我正在尝试从网站中提取图片的 URL。我是这方面的菜鸟,所以请多多包涵。基于 HTML 代码,我想要的图片类是“fotorama__img”。但是,当我执行我的代码时,它似乎不起作用。有谁知道为什么会这样?另外,src 属性为什么不包含整个 URL,只是其中的一部分?示例:图片的链接是https://www.supermicro.com/files_SYS/images/System/SYS-120U-TNR_callout_front.jpg,但img标签的src属性是"/files_SYS/images/System/sysThumb/SYS-120U-TNR_main.png"。

这是我的代码:

from bs4 import BeautifulSoup
import requests 

page = requests.get("https://www.supermicro.com/en/products/system/Ultra/1U/SYS-120U-TNR")
soup = BeautifulSoup(page.content,'lxml')
images = soup.find_all("img", {"class": "fotorama__img"})
for image in images:
    print(image.get("src"))

这是页面的 HTML 代码图片

感谢您的帮助!

【问题讨论】:

    标签: python html image beautifulsoup src


    【解决方案1】:

    类是通过 JavaScript 动态添加的,所以 beautifulsoup 看不到它。要从该站点提取图像,您可以执行以下操作:

    import requests
    from bs4 import BeautifulSoup
    
    page = requests.get(
        "https://www.supermicro.com/en/products/system/Ultra/1U/SYS-120U-TNR"
    )
    soup = BeautifulSoup(page.content, "lxml")
    images = [
        "https://www.supermicro.com" + a["href"]
        for a in soup.select(".fotorama > a")
    ]
    
    print(*images, sep="\n")
    

    打印:

    https://www.supermicro.com/files_SYS/images/System/SYS-120U-TNR_main.png
    https://www.supermicro.com/files_SYS/images/System/SYS-120U-TNR_callout_angle.jpg
    https://www.supermicro.com/files_SYS/images/System/SYS-120U-TNR_callout_top.jpg
    https://www.supermicro.com/files_SYS/images/System/SYS-120U-TNR_callout_front.jpg
    https://www.supermicro.com/files_SYS/images/System/SYS-120U-TNR_callout_rear.jpg
    

    【讨论】:

    • 成功了!!感谢您的快速评论。请问你为什么用href而不是src,(".fotorama >a")是什么意思?
    • @JakeNguyen 当您执行print(soup) 时,您会看到完整图像位于href= 属性中的<a> 标记内。 ".fotorama > a" 是 CSS 选择器:它的意思是“给我所有 <a> 直接在带有 class="fotorama" 的标签下的标签。
    • 我明白了。当我在 Google Chrome 上使用 Inspect 功能时,它没有显示环绕 标签的 标签,所以我有点困惑。还有很多东西要学。非常感谢。
    猜你喜欢
    • 2013-04-06
    • 2017-10-14
    • 1970-01-01
    • 2020-12-01
    • 2022-10-21
    • 2018-01-07
    • 2018-07-18
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多