python-3.x - 如何删除所有html标签并连接文本
问题描述
我正在使用 BeautifulSoup。
review =page_soup.findAll("div",{"class":"content"})
以下是我的评论的输出
review = [<div class="content">
<div class="text show-more__control">AAAAA.</div>
<div class="actions text-muted">
3 out of 8 found this helpful.
<span>
Was this review helpful? <a href="/registration/signin?ref_=urv"> Sign in</a> to vote.
</span>
<br/>
<a href="/review/rw1429145/?ref_=tt_urv">Permalink</a>
</div>
</div>, <div class="content">
<div class="text show-more__control">BBBBB.</div>
<div class="actions text-muted">
1 out of 2 found this helpful.
<span>
Was this review helpful? <a href="/registration/signin?ref_=urv"> Sign in</a> to vote.
</span>
<br/>
<a href="/review/rw2895175/?ref_=tt_urv">Permalink</a>
</div>
</div>]
我希望它变成这样的原始文本。
AAAAA.BBBBB.
解决方案
你可以text
继续div
上课show-more__control
。
divs=page_soup.find_all('div',class_="show-more__control")
texts=[x.text for x in divs]
print(''.join(texts))
如果show_more__control
存在于其他地方,您可以使用
contents=page_soup.find_all('div',class_="content")
texts=[x.find('div',class_='show-more__control').text for x in contents]
print(''.join(texts))
编辑:编辑答案以反映您问题的变化
原始问题的 html 和答案
html="""
<div class="content">
<div class="text show-more__control">AAAAA.<br/><br/>Ted's Evaluation -- 1 of 3: You can find something better to do with this part of your life.</div>
<div class="actions text-muted">
3 out of 8 found this helpful.
<span>
Was this review helpful? <a href="/registration/signin?ref_=urv"> Sign in</a> to vote.
</span>
<br/>
<a href="/review/rw1429145/?ref_=tt_urv">Permalink</a>
</div>
</div>, <div class="content">
<div class="text show-more__control">BBBBB.</div>
<div class="actions text-muted">
1 out of 2 found this helpful.
<span>
Was this review helpful? <a href="/registration/signin?ref_=urv"> Sign in</a> to vote.
</span>
<br/>
<a href="/review/rw2895175/?ref_=tt_urv">Permalink</a>
</div>
</div>
"""
from bs4 import BeautifulSoup
soup=BeautifulSoup(html,"html.parser")
divs=soup.find_all('div',class_="show-more__control")
texts=[x.contents[0] for x in divs]
print(''.join(texts))
输出:
AAAAA.BBBBB.
在这种情况下仅使用text
属性就会给出输出
AAAAA.Ted's Evaluation -- 1 of 3: You can find something better to do with this part of your life.BBBBB.
推荐阅读
- firebase - 创建文档引用时,Firestore 读取请求非常慢
- flutter - Cubit - Flutter 错误 - “查找已停用小部件的祖先是不安全的”
- postgresql - 调用 CreateModel 时如何设置角色?
- django - Django:forms.Form中的“对象没有属性获取”错误
- javascript - 位置 0 处的 JSON 中的意外标记
- python-3.x - Python 对象属性命名
- javascript - 代码可以在 PC 上运行,但不能在移动设备上运行
- prometheus - Prometheus 规则中是否存在变量之类的东西?
- reactjs - 在开发期间更新 React JS 中的模型类似乎会立即删除对数据的任何更改
- java - 如何删除我的工具栏Android上方的空白