【问题标题】:How to find tag by text with regex?如何使用正则表达式按文本查找标签?
【发布时间】:2017-01-16 16:28:30
【问题描述】:

我需要通过部分文本获取 HTML 标记。我找到了一些解决方案,但对我来说效果不佳。

from bs4 import BeautifulSoup
import re
soup = BeautifulSoup("""
<table>
    <tbody>
        <tr>
            <td style="width: 100px; height: 20px">
                <div style="font-size: 8.7pt">
                    Арт.: 
                    <span id="ContentPlaceHolder1_ContentPlaceHolder1_DataList2_Label12_0"> 1185A</span>
                    </div>
                <div style="font-size: 12pt; font-weight: bold;">
                    <span id="ContentPlaceHolder1_ContentPlaceHolder1_DataList2_LoginView3_0_Label12_0">I_CAN_GET_THIS other text</span>
                    I CAN NOT GET THIS?.
                </div>
            </td>
        </tr>
    </tbody>
</table>
""", 'lxml')
print(soup.find('span', text=re.compile('I_CAN_GET_THIS')))
print(soup.find('div', text=re.compile('I_CAN_NOT_GET_THIS')))

>>> <span id="ContentPlaceHolder1_ContentPlaceHolder1_DataList2_LoginView3_0_Label12_0">I_CAN_GET_THIS other text</span>
>>> None

所以我不明白为什么它在第二种情况下不起作用,我应该怎么做才能使它起作用? 谢谢

【问题讨论】:

    标签: regex python-3.x beautifulsoup


    【解决方案1】:

    text 参数(现在已重命名为 string 但仍受支持)将使用元素的 .string attribute,该元素将变为 None 如果有多个子元素

    如果一个标签包含多个东西,那么不清楚 .string 应该指什么,所以 .string 被定义为 None

    这正是您的目标 div 元素的情况 - 它有一个 span 子节点和一个文本节点。

    相反,您可以找到文本节点,然后获取它的父节点:

    soup.find(text=re.compile('I CAN NOT GET THIS')).parent
    

    或者,使用searching function,您可以使用.get_text() 组合子文本:

    soup.find(lambda tag: tag.name == 'div' and 'I CAN NOT GET THIS' in tag.get_text())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多