【发布时间】:2012-08-01 04:42:16
【问题描述】:
我正在寻找一种在 linux shell 环境中从 HTML 获取某些信息的方法。
这是我感兴趣的一点:
<table class="details" border="0" cellpadding="5" cellspacing="2" width="95%">
<tr valign="top">
<th>Tests</th>
<th>Failures</th>
<th>Success Rate</th>
<th>Average Time</th>
<th>Min Time</th>
<th>Max Time</th>
</tr>
<tr valign="top" class="Failure">
<td>103</td>
<td>24</td>
<td>76.70%</td>
<td>71 ms</td>
<td>0 ms</td>
<td>829 ms</td>
</tr>
</table>
我想存储在 shell 变量中,或者在从上面的 html 中提取的键值对中回显这些变量。示例:
Tests : 103
Failures : 24
Success Rate : 76.70 %
and so on..
目前我能做的是创建一个 java 程序,该程序将使用 sax 解析器或 html 解析器(如 jsoup)来提取此信息。
但是在这里使用 java 似乎是在您要执行的“包装器”脚本中包含可运行 jar 的开销。
我确信肯定有“shell”语言可以做同样的事情,例如 perl、python、bash 等。
我的问题是我对这些的经验为零,有人可以帮我解决这个“相当简单”的问题
快速更新:
我忘了提到我在 .html 文档中有更多表格和更多行,对此我感到抱歉(清晨)。
更新 #2:
尝试像这样安装 Bsoup,因为我没有 root 访问权限:
$ wget http://www.crummy.com/software/BeautifulSoup/bs4/download/4.0/beautifulsoup4-4.1.0.tar.gz
$ tar -zxvf beautifulsoup4-4.1.0.tar.gz
$ cp -r beautifulsoup4-4.1.0/bs4 .
$ vi htmlParse.py # (paste code from ) Tichodromas' answer, just in case this (http://pastebin.com/4Je11Y9q) is what I pasted
$ run file (python htmlParse.py)
错误:
$ python htmlParse.py
Traceback (most recent call last):
File "htmlParse.py", line 1, in ?
from bs4 import BeautifulSoup
File "/home/gdd/setup/py/bs4/__init__.py", line 29
from .builder import builder_registry
^
SyntaxError: invalid syntax
更新 #3:
Running Tichodromas 的回答得到这个错误:
Traceback (most recent call last):
File "test.py", line 27, in ?
headings = [th.get_text() for th in table.find("tr").find_all("th")]
TypeError: 'NoneType' object is not callable
有什么想法吗?
【问题讨论】:
-
有一个不错的 python 库可能会有所帮助:BeautifulSoup -> crummy.com/software/BeautifulSoup/bs4/doc .
-
@Jakob S. 谢谢你的评论,因为我告诉过你我是新手所以我下载了 tarbal 并尝试安装它
python setup.py install得到这个权限错误error: could not create '/usr/lib/python2.4/site-packages/bs4': Permission denied,我该怎么做指定安装它的目录。安装其他命令时有没有类似-prefix的东西 -
我不得不承认,如果您没有 root 访问权限,我不确定如何实现这一点 - 而且我目前没有 Linux 可以尝试。原则上,应该可以简单地将包复制到相对于源 .py 文件的正确目录,以便解释器可以找到它。
-
查看文档:“如果一切都失败了,Beautiful Soup 的许可允许您将整个库与您的应用程序打包在一起。您可以下载 tarball,将其 bs4 目录复制到应用程序的代码库中,然后无需安装即可使用 Beautiful Soup。” (crummy.com/software/BeautifulSoup/bs4/doc/…)
-
您可以/应该将 bs4 安装在单独的 virtualenv 中。您将在其中拥有伪 root 权限。