regex - 如何使用正则表达式按文本查找标签?

标签 regex python-3.x beautifulsoup

我需要通过其文本的一部分获取 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

所以我无法理解为什么它在第二种情况下不起作用以及我应该做什么才能使它起作用? 谢谢

最佳答案

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

If a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to be None

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

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

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

或者,使用 searching function你会在哪里使用 .get_text()它结合了 child 文本:

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

关于regex - 如何使用正则表达式按文本查找标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41680838/

相关文章:

javascript - 将输入限制为在 IE 中使用大写字符的特定正则表达式

python - beautifulsoup 无法使用正则表达式在文件中找到 href

regex - 在10-K Edgar文件中使用Beautifulsoup和正则表达式提取文本

python - 使用 python 和 BeautifulSoup 从网页中检索链接

javascript - 正则表达式 - 组合正则表达式 - 字符串的开头和结尾

javascript - 正则表达式根据下一个单词将 a 更改为 an

Python如何在数据框中应用.replace以更改大量值

python - 无法解析网页中的不同产品链接

python-3.x - 雅虎财经 ValueError : zero-size array to reduction operation maximum which has no identity

Python:使用与不带空格的字符串输入匹配的文本文件查找单词