首页 > 解决方案 > BeautifulSoup 在标签中查找部分字符串

问题描述

由于某种原因,BeautifulSoup 突然无法在我开始的新 Python 脚本中找到我的任何标签的内容。我已经使用 BeautifulSoup 大约一年了,从来没有遇到过这个问题。

我能够使用“ .json () ”在 Python 中成功注入 JSON 有效负载,使用html.parser将其传递给 BeautifulSoup,并且每次都可以正常工作。

我现在正在尝试读取包含原始 HTML 的 MySql 字段,将其作为文本字符串输入 Python,然后使用 BeautifulSoup 解析和操作,但没有任何成功。

我已经尝试简单地加载一个文本字符串,就像在这个例子中一样,具有相同的否定结果 = 无法找到一个标签,基于文本字符串搜索(BeautifulSoup 总是返回 =“”)。

text_field = '<td><p></p><p></p><td><p>HELP text here 1<a href="some_URL_here"><ac:image ac:align="center" ac:layout="center" ac:original-height="153" ac:original-width="200"><ri:attachment ri:filename="image.png" ri:version-at-save="1"></ri:attachment></ac:image></a></p></td><p /><h2 style="text-align: center;"><a href="{some_URL_here}"><em><strong>Click here&hellip;</strong></em></a></h2></td>'
soup = BeautifulSoup(text_field, 'html.parser')
print(soup)
print (soup.prettify())

test = soup.find('td', text="HELP")
print(test)

BeautifulSoup 正确解析了我的“美化”的输出:

<td>
    <p>
    </p>
    <p>
    </p>
    <td>
        <p>
            HELP text here 1
            <a href="some_URL_here">
                <ac:image ac:align="center" ac:layout="center" ac:original-height="153" ac:original-width="200">
                    <ri:attachment ri:filename="image.png" ri:version-at-save="1">
                    </ri:attachment>
                </ac:image>
            </a>
        </p>
    </td>
    <p>
    </p>
    <h2 style="text-align: center;">
        <a href="{some_URL_here}">
            <em>
                <strong>
                    Click here…
                </strong>
            </em>
        </a>
    </h2>
</td>

但无论我尝试什么,BeautifulSoup 总是从任何查找请求中返回“无”。

我在这里遗漏了一些明显的东西吗?

标签: pythonstringbeautifulsouptagsfind

解决方案


所以发现我不能对字符串的部分部分进行查找。所以而不是:

test = soup.find('td', text="HELP")

你必须这样做:

test = soup.find('td', text="HELP text here 1")

你必须声明整个刺痛。

在您想搜索部分字符串的情况下,我使用RegEX试错法结合以下帖子找到了答案:

Beautiful Soup 根据部分属性值查找标签

python的re:如果字符串包含正则表达式模式,则返回True

所以解决方案如下所示:

真实输入示例(Python)

INPUT = <tbody><tr><th colspan="2"><h3><strong>TITLE 1</strong></h3></th></tr><tr><td><p><strong>TITLE 2</strong></p></td><th><p><strong>File and documentation repository</strong></p></th></tr><tr><td><ac:image ac:align="center" ac:layout="center" ac:original-height="912" ac:original-width="1502"><ri:attachment ri:filename="Sample_Diagram.jpg" ri:version-at-save="1"></ri:attachment></ac:image></td></tr></tbody>

.... 这是 Python 脚本:

REPLACEMENT_TAG = '<ri:attachment ri:filename="new_filename.png" ri:version-at-save="1"></ri:attachment>'
    
    
soup = BeautifulSoup(INPUT, "html.parser")
    
EXTRACTED = soup.find("ri:attachment", {"ri:filename" : re.compile(r'Sample_Diagram.jpg')})
EXTRACTED.replaceWith(REPLACEMENT_TAG)

此 Python 代码将:

  • 识别标签(即“ri:attachment”
  • 基于部分字符串(即“Sample_Diagram.jpg”
  • 并替换为新的 TAG

推荐阅读