【问题标题】:Beautiful Soup: get picture size from htmlBeautiful Soup:从 html 获取图片大小
【发布时间】:2016-04-20 20:37:16
【问题描述】:

我想使用 Bueatiful Soup 提取图片的宽度和高度。所有图片的代码格式相同:

<img src="http://somelink.com/somepic.jpg" width="200" height="100">

我可以很容易地提取链接

for pic in soup.find_all('img'):
    print (pic['src'])

但是

for pic in soup.find_all('img'):
    print (pic['width'])

不适用于提取尺寸。我错过了什么?

编辑: 页面中的其中一张图片没有html代码中的宽度和高度。在最初的帖子中没有注意到这一点。所以任何解决方案都必须考虑到这一点

【问题讨论】:

    标签: python image beautifulsoup


    【解决方案1】:

    类似字典的属性访问也应该适用于widthheight,如果它们被指定的话。您可能会遇到没有明确设置这些属性的图像 - 在这种情况下,您当前的代码会抛出 KeyError。您可以使用 get() 并提供默认值:

    for pic in soup.find_all('img'):
        print(pic.get('width', 'n/a'))
    

    或者,您只能找到指定了widthheightimg 元素:

    for pic in soup.find_all('img', width=True, height=True):
        print(pic['width'], pic['height']) 
    

    【讨论】:

    • 有一张图片没有明确的宽度和高度,但get() 为该特定图片返回None
    • @horace_vr 当然,如果未设置宽度,pic.get('width') 将返回 None。与pic['width'] 的情况下的KeyError 不同。
    【解决方案2】:

    获取其他属性有点不同

    for pic in soup.find_all('img'):
        print(pic.get('width'))
    

    【讨论】:

      【解决方案3】:

      试试这个:

      >>> html = '<img src="http://somelink.com/somepic.jpg" width="200" height="100">'
      >>> soup = BeautifulSoup(html)
      >>> for tag in soup.find_all('img'):
      ...     print tag.attrs.get('height', None), tag.attrs.get('width', None)
      ... 
      100 200
      

      你可以使用 attrs 方法,它返回一个 dict ,键作为标签的属性,值作为标签的值。

      【讨论】:

        猜你喜欢
        • 2017-10-22
        • 1970-01-01
        • 2020-10-24
        • 2022-01-05
        • 1970-01-01
        • 2017-01-17
        • 2015-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多