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
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'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With