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

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

概述我正在使用BeautifulSoup 4尝试对字符串列表进行迭代并替换子字符串,但是在对字符串生成器进行迭代时执行replace_with会早早退出循环,这是一个问题.例如,给出此代码from bs4 import BeautifulSoup s = BeautifulSoup('<p>a</p><p>b</p&g

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

例如,给出此代码

from bs4 import BeautifulSoups = 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 BeautifulSoups = 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>aNone

在replace_with()之后,next_element为None.

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

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

from bs4 import BeautifulSoups = 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=nextprint(s)

输出量

<p>replace</p><p>replace</p><p>replace</p>
总结

以上是内存溢出为你收集整理的替换BeautifulSoup迭代器中的字符串提早退出? 全部内容,希望文章能够帮你解决替换BeautifulSoup迭代器中的字符串提早退出? 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1199463.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存