python - 如何在beautifulsoup中有条件地从html中提取文本

标签 python html beautifulsoup

我正在尝试使用以下 html 从网站中提取特定文本:

              ...
               <tr>
                <td>
                 <strong>
                  Location:
                 </strong>
                </td>
                <td colspan="3">
                 90 km S. of Prince Rupert
                </td>
               </tr>
              ...

我想提取“位置:”之后的文本(即“鲁珀特王子港南 90 公里”)。我想循环浏览大量类似的网站并获取“位置:”后面的文本

我对 python 很陌生,无法找到基于这样的条件提取文本的解决方案。

最佳答案

我的理解是 BS 不能像 LXML 那样处理格式错误的 html。然而,我可能是错的,但我通常使用 lxml 来处理这些类型的问题。您可以使用以下一些代码来更好地了解如何使用这些元素。有很多方法。

我认为获取 lxml 的最佳位置是 here

from lxml import html

ms = '''<tr>
            <td>
             <strong>
              Location:
             </strong>
            </td>
            <td colspan="3">
             90 km S. of Prince Rupert
            </td>
            <mytag>
            Hello World
            </mytag>
           </tr>'''

mytree = html.fromstring(ms)  #this creates a 'tree' in memory
for e in mytree.iter():       # iterate through the elements
    if e.tag == 'td':         #focus on the elements that are td elements
        if 'location' in e.text_content().lower(): # if location is in the text of a td
            for sib in e.itersiblings(): # find all the siblings of the td
                sib.text_content()   # print the text

'\n 鲁珀特王子港以南 90 公里\n

这里有很多东西需要学习,但 lxml 非常内省(introspection)

>>> help (e.itersiblings)
Help on built-in function itersiblings:

itersiblings(...)
    itersiblings(self, tag=None, preceding=False)

    Iterate over the following or preceding siblings of this element.

The direction is determined by the 'preceding' keyword which
defaults to False, i.e. forward iteration over the following
siblings.  When True, the iterator yields the preceding
siblings in reverse document order, i.e. starting right before
the current element and going left.  The generated elements
can be restricted to a specific tag name with the 'tag'
keyword.

注意 - 我稍微更改了字符串并添加了 mytag,因此请参阅基于 itersiblings 帮助的新代码

for e in mytree.iter():
    if e.tag == 'td':
        if 'location' in e.text_content().lower():
            for sib in e.itersiblings(tag = 'mytag'):
                sib.text_content()


 '\n                hello world\n 

关于python - 如何在beautifulsoup中有条件地从html中提取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22107328/

相关文章:

javascript - 用于在多个 div 中 chop 文本的单个脚本

javascript - 如何过渡堆叠的 Div。在 JavaScript 中

python - 是否可以使用 Beautifulsoup 修改链接值而不重新创建所有链接?

Python打印函数不按顺序打印

python - 对 setup.py 中的 package_dir 和 packages 设置感到困惑

python - 使用用户输入验证生成的验证码

javascript - 我有两个单选按钮,但即使我们选择不同的单选按钮,表单也只能获取一个单选按钮值

python - 在 Python 中使用 BeautifulSoup 库

python - 从 AppEngine 上的 Python 开始

python - 在 python 中处理大型数据池