替换BeautifulSoup迭代器中的字符串提早退出?

前端之家收集整理的这篇文章主要介绍了替换BeautifulSoup迭代器中的字符串提早退出? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用BeautifulSoup 4尝试对字符串列表进行迭代并替换子字符串,但是在对字符串生成器进行迭代时执行replace_with会早早退出循环,这是一个问题.

例如,给出此代码

from bs4 import BeautifulSoup

s = BeautifulSoup("<p>a</p><p>b</p><p>c</p>",features="html.parser")
for st in s.strings:
  st.replace_with('replace')

s的最终含量将是p的替换值p / b的p / c的p / c的p / p的值,而预期的行为是a,b和c分别为更换.调试器的逐步调试可确认替换发生后,字符串迭代将暂停,基本上只执行一次迭代并提早退出.

在实践中,我将更新字符串的小节,并用新创建的BeautifulSoup对象替换它们,因此,更简单的替换方法可能不起作用:

updated = st.replace(keyword,f'<a href="url/{keyword}">{keyword}</a>')
st.replace_with(BeautifulSoup(updated,features="html.parser"))

解决方法或更正确的方法吗?

最佳答案
您将获得此输出b’coz,如replace_with()文档中所述

PageElement.replace_with() removes a tag or string from the tree,and
replaces it with the tag or string of your choice

一旦从树中删除,它将不再具有next_element,并且发电机会提前退出.我们可以使用此代码进行检查

from bs4 import BeautifulSoup
s = BeautifulSoup("<p>a</p><p>b</p><p>c</p>",features="html.parser")
for st in s.strings:
    print(st.next_element)
    st.replace_with('replace')
    print(st)
    print(st.next_element)

输出

<p>b</p>
a
None

在replace_with()之后,next_element为None.

一种方法是@cody即提及的方法.使用list()一次获取值的所有值.

另一种方法是存储next_element并将其设置在replace_with()之后,以使生成器产生更多元素.

from bs4 import BeautifulSoup
s = BeautifulSoup("<p>a</p><p>b</p><p>c</p>",features="html.parser")
for st in s.strings:
    next=st.next_element
    st.replace_with('replace')
    st.next_element=next
print(s)

输出

<p>replace</p><p>replace</p><p>replace</p>
原文链接:https://www.f2er.com/python/533069.html

猜你在找的Python相关文章