Python 美丽的汤:从html获取图片大小
我想用美味汤提取图片的宽度和高度。所有图片具有相同的代码格式:Python 美丽的汤:从html获取图片大小,python,image,beautifulsoup,Python,Image,Beautifulsoup,我想用美味汤提取图片的宽度和高度。所有图片具有相同的代码格式: <img src="http://somelink.com/somepic.jpg" width="200" height="100"> 但是 无法提取大小。我错过了什么 编辑: 页面中的一张图片没有html代码中的宽度和高度。在最初发布时没有注意到这一点。因此,任何解决方案都必须考虑到这一点它的工作原理稍有不同,以获得其他属性 for pic in soup.find_all('img'): print(pi
<img src="http://somelink.com/somepic.jpg" width="200" height="100">
但是
无法提取大小。我错过了什么
编辑:
页面中的一张图片没有html代码中的宽度和高度。在最初发布时没有注意到这一点。因此,任何解决方案都必须考虑到这一点它的工作原理稍有不同,以获得其他属性
for pic in soup.find_all('img'):
print(pic.get('width'))
它的工作原理稍有不同,可以获得其他属性
for pic in soup.find_all('img'):
print(pic.get('width'))
如果指定了
width
和height
,则类似于字典的属性访问也应该适用。您可能会遇到没有明确设置这些属性的图像-在这种情况下,您当前的代码将抛出一个KeyError
。您可以使用get()
并提供默认值:
for pic in soup.find_all('img'):
print(pic.get('width', 'n/a'))
或者,您只能找到指定了宽度和高度的img
元素:
for pic in soup.find_all('img', width=True, height=True):
print(pic['width'], pic['height'])
如果指定了width
和height
,则类似于字典的属性访问也应该适用。您可能会遇到没有明确设置这些属性的图像-在这种情况下,您当前的代码将抛出一个KeyError
。您可以使用get()
并提供默认值:
for pic in soup.find_all('img'):
print(pic.get('width', 'n/a'))
或者,您只能找到指定了宽度和高度的img
元素:
for pic in soup.find_all('img', width=True, height=True):
print(pic['width'], pic['height'])
试试这个:
>>> 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
>html=''
>>>soup=BeautifulSoup(html)
>>>用于汤中的标记。查找所有('img'):
... 打印tag.attrs.get('height',None),tag.attrs.get('width',None)
...
100 200
您可以使用attrs方法,它返回一个dict,keys作为标记的属性,value作为标记值。尝试以下操作:
>>> 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
>html=''
>>>soup=BeautifulSoup(html)
>>>用于汤中的标记。查找所有('img'):
... 打印tag.attrs.get('height',None),tag.attrs.get('width',None)
...
100 200
您可以使用attrs方法,它返回一个dict,keys作为标记的属性,value作为标记的值。有一张图片没有明确的宽度和高度,但是get()
返回该特定的None
picture@horace_vr当然,如果未设置宽度,pic.get('width')
将返回None
。与pic['width']
情况下的keyrerror
相反,有一张图片没有明确的宽度和高度,但是get()
返回该特定的None
picture@horace_vr当然,如果未设置宽度,pic.get('width')
将返回None
。与pic['width']
情况下的键错误相反。