html - 使用 BeautifulSoup,我可以在标签之间获取带有其他字符串的文本以将它们分开吗?
问题描述
所以,我一直在用 BeautifulSoup 进行爬行,但我遇到了一些乱七八糟的 html 标签。
这是一个例子:
<html>
<body>
<p>Hey</p>
<div>
<div>
<span class="date">0817</span>
</div>
</div>
<p>I want all of those</p>
<div>
<div>
<p>But I want to get those separately</p>
<div>
</div>
<p>Hope this work</p>
</body>
</html>
所以如果我使用这样的代码:
soup = BeautifulSoup(html,'html.parser')
body = soup.find("body")
print(body.text)
我可能会得到这个:
"Hey0817I want all of thoseBut I want to get those separatelyHope this work"
问题是,我可以得到那些带有一些字符串作为分隔符的文本吗?分隔其他标签之间的东西的分隔符如:
"@@@Hey@@@0817@@@Iwant all of those@@@But I want to get those separately@@@Hope this work"
or
"Hey@@@0817@@@Iwant all of those@@@But I want to get those separately@@@Hope this work@@@"
or
"Hey@@@0817@@@Iwant all of those@@@But I want to get those separately@@@Hope this work"
这样我以后就可以通过“@@@”将这些文本与其他代码分开?或者有没有做类似事情的周边?任何建议都会很有帮助。感谢您的关注和时间!希望你能给我解惑。
解决方案
如果你想要一个列表,你可以使用:
item_text = [t.text for t in body.find_all()]
如果你真的想要分隔符:
body.get_text('@@@')
推荐阅读
- python - 根据Python中的时间间隔将时间范围拆分为多个时间段
- powershell - 通过powershell取出字符串的特定部分
- c# - Microsoft Graph API - 如何使用“skiptoken”
- javascript - 在javascript中无限期显示通知
- c - 如何只打印字符串中不重复的字符?
- python - 将 40x5 矩阵插入 1000x1000x3 的 3 维数组
- json - UISearchBar 通过 UITableView 和 JSON
- python - dlib 寻找不正确的 CUDA 版本
- python - 将 .txt 数据保存在 Excel 工作表中
- maven - 多模块项目中的 Spot bugs / Maven 构建