在PHP或Python中提取HTML数据

1 投票
3 回答
1738 浏览
提问于 2025-04-16 08:45

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

比如说,像“股本”这样的内容 -> array (30.36, 17, 17 .... 等等) 这样的格式会很有帮助。

<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中完成这个任务呢?

3 个回答

2

BeautifulSoup 是一个用于处理网页数据的工具。

2

别忘了在Python中使用lxml这个库。它也很适合用来提取数据。虽然安装起来有点麻烦,但运行速度更快。你可以在这里找到它的安装链接:http://pypi.python.org/pypi/lxml/2.2.8

5

一个不错的起点是使用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),可以完成任务!

撰写回答