beautifulsoup - 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>
解决方案
找到了一个简单的解决方案。您可以简单地将字符串设置为相等,而不是使用替换。
item.string = 'Some TEST string'
推荐阅读
- javascript - 发送数据并保存在文本字段中
- django - Django注册组:组匹配查询不存在
- c# - Windows 窗体 RDLC:将项目更新为包引用格式后缺少程序集
- java - 使用正则表达式在java中拆分字符串
- swift - 如何将单元格固定在 Tableview 中的选择上?
- http - Set-Cookie 的哪一部分应该发送到服务器?
- r - 试图运行这个广义线性模型来发现多个随机效应对蟋蟀质量的影响,我得到了以下错误
- agora.io - 从 Web SDK 到 iOS SDK 的视频通话
- html - 身体标签看到了相同类型的元素
- git - 未跟踪的忽略文件仍然出现在 git status 中