Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beautiful Soup: get picture size from html

I want to extract the pictures' widths and heights using Bueatiful Soup. All pictures have the same code format:

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

I can extract the links easily with

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

But

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

is not working for extracting sizes. What am I missing?

EDIT: One of the pictures in the page does not have the width and height in the html code. Did not notice this at the time of the initial post. So any solution must take this into account

like image 887
horace_vr Avatar asked Sep 21 '25 00:09

horace_vr


1 Answers

The dictionary-like attribute access should work for width and height as well, if they are specified. You might encounter images that don't have these attributes explicitly set - your current code would throw a KeyError in this case. You can use get() and provide a default value instead:

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

Or, you can find only img elements that have the width and height specified:

for pic in soup.find_all('img', width=True, height=True):
    print(pic['width'], pic['height']) 
like image 173
alecxe Avatar answered Sep 22 '25 15:09

alecxe