首页 > 解决方案 > BeautifulSoup - .string 为空

问题描述

当我.string与 BeautifulSoup 一起使用时,它应该返回文本/内容。但是当我在下面这样的项目上执行此操作时,它不会返回任何内容。我正在尝试替换 theis html 元素中的字符串/文本,这需要使用.string.replace_with(). 所以简单地使用item.text, 在这里不是一个选项。那么我怎样才能让它返回该内容,以便我能做到.replace_with()呢?

from bs4 import BeautifulSoup

html = '''<p class="text">If you saw the movie "<em>The Devil's Advocate (1997)"</em>, perhaps you remember the end. Milton proposes to Kevin to take over his company, promising that he will have everything in the world, but with a single price - to sell his soul. But Kevin was hiding virtues that Milton did not believe that he has them.</p>'''
soup=BeautifulSoup(html, 'html.parser')    
item = soup.find('p', {'class':"text"})   

item.string

所以如果我这样做:

item.string.replace_with('Some TEST string')

我会收到一个错误AttributeError: 'NoneType' object has no attribute 'replace_with',因为item.string返回None

我期望输出是:

print(item)
<p class="text">Some TEST string</p>

标签: beautifulsoup

解决方案


找到了一个简单的解决方案。您可以简单地将字符串设置为相等,而不是使用替换。

item.string = 'Some TEST string'

推荐阅读