【发布时间】:2016-01-14 01:37:47
【问题描述】:
我需要获取 html 文档的平均 div 高度和宽度。
我已经尝试过这个解决方案,但它不起作用:
import numpy as np
average_width = np.mean([div.attrs['width'] for div in my_doc.get_div() if 'width' in div.attrs])
average_height = np.mean([div.attrs['height'] for div in my_doc.get_div() if 'height' in div.attrs])
print average_height,average_width
get_div方法返回beautifulSoup的find_all方法检索到的所有div的列表
这是一个例子:
print my_doc.get_div()[1]
<div style="position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:81px; width:127px; height:9px;">
<span style="font-family: EICMDA+AdvTrebu-R; font-size:8px">Journal of Infection (2015)
</span>
<span style="font-family: EICMDB+AdvTrebu-B; font-size:8px">xx</span>
<span style="font-family: EICMDA+AdvTrebu-R; font-size:8px">, 1</span>
<span style="font-family: EICMDD+AdvPS44A44B; font-size:7px">e</span>
<span style="font-family: EICMDA+AdvTrebu-R; font-size:8px">4
<br/>
</span>
</div>
当我得到属性时,它完美地工作
print my_doc.get_div()[1].attrs
{u'style': u'position:absolute; border: textbox 1px solid; writing-mode:lr-tb; left:45px; top:81px; width:127px; height:9px;'}
但是当我尝试获取价值时
print my_doc.get_div()[1].attrs['width']
我收到一个错误:
KeyError: 'width'
但我不明白,因为当我检查类型时:
print type(my_doc.get_div()[1].attrs)
这是一本字典,<type 'dict'>
【问题讨论】:
-
你用的是 numpy 的意思吗?你能给出页面的url或更多html源吗?
-
@SIslam ,我已经编辑了我的帖子
-
如何计算
div的宽度?示例:我将div设置为 100% 宽度。如果我的窗口是全屏的,大概是~1900px。如果我的窗口更小,div更小。那么它的宽度是多少呢? “平均”的概念是怎么来的? -
@Two-BitAlchemist,在 html 输入中,为 style 属性中的所有 div 指定了宽度和高度,对于所有 div,它是相同的单位度量,所以我只需要获取这些值并计算均值/平均值,均值将作为参考值去除本文档中一些无用的片段,因此与屏幕大小无关
-
attrs是一个单条目字典,键为style,值为包含文本宽度*的字符串。您必须自己解析字符串以提取宽度属性。
标签: python html beautifulsoup