php - Beautiful Soup [Python] 和表格中文本的提取

标签 php python

我也是 Python 和 Beatiful Soup 的新手!我听说了 BS。它被认为是解析和提取内容的好工具。所以我在这里......:

我想在html中取一个表格的第一个td的内容 文档。比如我有这张表

<table class="bp_ergebnis_tab_info">
    <tr>
            <td>
                     This is a sample text
            </td>

            <td>
                     This is the second sample text
            </td>
    </tr>
</table>

如何使用 beautifulsoup 获取文本“This is a sample text”? 我使用 soup.findAll('table' ,attrs={'class':'bp_ergebnis_tab_info'}) 来获取 整张 table 。

谢谢...或者我应该尝试用 Perl 来获取全部内容...我不太熟悉。另一个解决方案是 PHP 中的正则表达式。

查看目标[1]:http://www.schulministerium.nrw.de/BP/SchuleSuchen?action=799.601437941842&SchulAdresseMapDO=142323

注意;由于 html 有点无效 - 我认为我们必须进行一些清理。这会导致大量的 PHP 代码——因为我们想用 PHP 解决这个问题。 Perl 也是一个很好的解决方案。

非常感谢您提供一些起点的提示和想法 零

最佳答案

首先找到表(就像你正在做的那样)。使用 find 而不是 findall 返回列表中的第一项(而不是返回所有发现的列表 - 在这种情况下我们必须添加额外的 [0] 取列表的第一个元素):

table = soup.find('table' ,attrs={'class':'bp_ergebnis_tab_info'})

然后再次使用find找到第一个td:

first_td = table.find('td')

然后使用renderContents()提取文本内容:

text = first_td.renderContents()

... 工作完成(尽管您可能还想使用 strip() 删除前导和尾随空格:

trimmed_text = text.strip()

这应该给出:

>>> print trimmed_text
This is a sample text
>>>

根据需要。

关于php - Beautiful Soup [Python] 和表格中文本的提取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4416013/

相关文章:

php多维排序

php - Silverstripe UserForms - 从 DataObject 填充选项

php - 去除除 src 之外的所有 HTML 属性

python - 如何从 Ubuntu 19.10 卸载 python 3.7?

Python:在关键字前后抓取文本

php - 在 laravel 5.4 中上传图片时移动 'tmp' 目录不起作用

php - jquery自动完成返回数据

python - "late binding closures"是什么意思?

python - 无法使用pythons mysqldb执行mysql插入

python - Google Identity Toolkit (v3) 是否与 GAE/python 沙箱兼容?