Skip to main content
 首页 » 编程设计

php之在 PHP 或 Python 中从 HTML 中提取数据

2025年05月04日18leader

我需要提取这些数据并从中显示一个简单的图表。

类似股权资本的东西 -> array (30.36, 17, 17 .... etc) 会有所帮助。

<html:tr> 
<html:td>Equity Share Capital</html:td> 
<html:td class="numericalColumn">30.36</html:td> 
<html:td class="numericalColumn">17.17</html:td> 
<html:td class="numericalColumn">15.22</html:td> 
<html:td class="numericalColumn">9.82</html:td> 
<html:td class="numericalColumn">9.82</html:td> 
</html:tr> 

如何在 PHP 或 Python 中完成此任务?

请您参考如下方法:

开始寻找的好地方是 python 模块 BeautifulSoup它提取文本并将其放入表格中。

假设您已将数据加载到名为 raw 的变量中:

from BeautifulSoup import BeautifulSoup 
soup = BeautifulSoup(raw) 
 
for x in soup.findAll("html:td"): 
   if x.string == "Equity share capital": 
       VALS = [y.string for y in x.parent.findAll() if y.has_key("class")] 
 
print VALS 

这给出:

[u'30.36', u'17.17', u'15.22', u'9.82', u'9.82'] 

您会注意到这是一个 unicode 字符串列表,请确保在处理之前将它们转换为您想要的任何类型。

通过 BeautifulSoup 有很多方法可以做到这一点。然而,我发现的好处是,快速破解通常足以 (TM) 完成工作!