加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 17:36:04 所属栏目:Python 来源:网络整理
导读:我正在使用BeautifulSoup 4尝试对字符串列表进行迭代并替换子字符串,但是在对字符串生成器进行迭代时执行replace_with会早早退出循环,这是一个问题. 例如,给出此代码 from bs4 import BeautifulSoups = BeautifulSoup("pa/ppb/ppc/p",features="html.parser"

我正在使用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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读