BeautifulSoup - 修改Tag的内容

2024-04-16 06:25:26 发布

您现在位置:Python中文网/ 问答频道 /正文

给定值为bs4.BeautifulSoup("<tr><td>Hello!</td><td>World!</td></tr>")的对象soup,如何从所有tr标记中删除感叹号?你知道吗

最接近的是:

for tr in soup.find_all("tr"):
    tr.string = tr.decode_contents().replace("!", "")

但这会导致:

<html><body><tr>&lt;td&gt;Hello&lt;/td&gt;&lt;td&gt;World&lt;/td&gt;</tr></body></html>

其中,decode_contents()中的尖括号在分配给tr.string时进行编码。你知道吗

我还尝试了tr.replace_with(str(tr).replace("!", ""))(使用Tag对象的HTML表示),得到了相同的结果。你知道吗

请记住,这是一个简化的示例。虽然我可以在这个特定的例子中迭代td标记,但实际上那些标记也包含HTML结构,这就带来了同样的问题。你知道吗


Tags: 对象标记ltgthelloworldstringhtml
2条回答

您可以尝试遍历作为<tr>子对象的所有字符串对象。你知道吗

import bs4

soup = bs4.BeautifulSoup("<table><tr><td>Hello!</td><td>World!</td></tr></table>")

for tr in soup.find_all("tr"):
    strings = list(tr.strings)
    for s in strings:
        new_str = s.replace("!", "")
        s.replace_with(new_str)

一个问题是,如果不中断迭代器,就无法替换.strings返回的字符串,这就是为什么我首先将其作为列表。如果这是一个问题,您可以在替换下一个元素之前以保留该元素的方式进行迭代,如下所示:

def iter_strings(elem):
    # iterate strings so that they can be replaced
    iter = elem.strings
    n = next(iter, None)
    while n is not None:
        current = n
        n = next(iter, None)
        yield current

def replace_strings(element, substring, newstring):
    # replace all found `substring`'s with newstring
    for string in iter_strings(element):
        new_str = string.replace(substring, newstring)
        string.replace_with(new_str)

for tr in soup.find_all("tr"):
    replace_strings(soup, "!", "")

执行了以下操作:

import bs4

soup = bs4.BeautifulSoup("<tr><td>Hello!</td><td>World!</td></tr>", "html.parser")

for tr in soup.find_all("tr"):
    replaced_tr = str(tr).replace("!", "")
    modified_tr = bs4.BeautifulSoup(replaced_tr, "html.parser").tr
    tr.replace_with(modified_tr)

似乎replace_with不适用于HTML字符串,因此应该首先创建一个BeautifulSoup对象,并将其用作replace_with的参数

相关问题 更多 >