【问题标题】:python BeautifulSoup - can't set attribute, trying to replace a tags valuepython BeautifulSoup - 无法设置属性,试图替换标签值
【发布时间】:2019-09-12 04:22:02
【问题描述】:

我正在尝试检查 span 标签是否有字符串'~',如果有,我想用'0'替换它。

我有数百个 span 标签,我想更改 span.text 值,因为我想将 IF 语句复制到我的代码中的许多地方,它不会努力将 var001 编码到 if 语句中。

我该怎么做?

我的代码

span = soup.find("span", id="id001")
if span.text in  ['~']:
    span.text = 0
var001 = span.text

但这给出了错误

AttributeError: can't set attribute

【问题讨论】:

    标签: python beautifulsoup tags


    【解决方案1】:

    在 bs4 4.7.1+ 中,您可以使用 :contains 来识别相关标签并利用 string.replace_with 更改 .text。 ~ 需要转义以将其与一般的兄弟组合器区分开来

    from bs4 import BeautifulSoup as bs
    
    html = '''<span>some text ~ </span>
    <span>some text</span>
    <span>some ~ text</span>
    <span>some text</span>
    <span>~ some text</span>'''
    
    soup = bs(html, 'lxml')
    
    for t in soup.select('span:contains(\~)'):
        t.string.replace_with('0')
    print(soup)
    

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2020-04-06
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2013-04-06
      • 1970-01-01
      相关资源
      最近更新 更多