python - Python BeautifulSoup 如何定位跨度?
问题描述
我一直试图在 HTML 页面上找到一个跨度,它不起作用。有人可以给我代码吗?十分感谢。
<div ng-repeat="m in messages" ng-if="hasMessage(m.message)" class="message-box success" ng-class="{ 'error': m.type == 'error', 'success': m.type == 'success', 'info': m.type == 'info', 'promotion': m.type == 'promotion' }"> <span ng-bind-html="m.message">Congratulations! Your $60 discount has been applied, enjoy $20 off your first 3 boxes.</span> <!----> </div>
我试过这段代码
soup = BeautifulSoup(r.text)
badges = soup.body.find('span', attrs={'class': 'message-box'})
for span in badges.span.find_all('span', recursive=False):
print(span.attrs['title'])
我想得到60美元的部分。
解决方案
您可以使用 BeautifulSoup 选择句子,但要获得该$60
部分,您必须使用其他技术,例如re
模块:
txt = '''<div ng-repeat="m in messages" ng-if="hasMessage(m.message)" class="message-box success" ng-class="{ 'error': m.type == 'error', 'success': m.type == 'success', 'info': m.type == 'info', 'promotion': m.type == 'promotion' }"> <span ng-bind-html="m.message">Congratulations! Your $60 discount has been applied, enjoy $20 off your first 3 boxes.</span> <!----> </div>'''
import re
from bs4 import BeautifulSoup
soup = BeautifulSoup(txt, 'html.parser')
text = soup.select_one('span[ng-bind-html="m.message"]').text
print( re.search(r'(\$\d+)', text).group(1) )
印刷:
$60
推荐阅读
- plot - 从最近的错误值绘制时间序列价格范围日期与日期时间框架不匹配
- shinyapps - 如何为闪亮的应用程序制作安装文件?
- ios - 使用 Flutter/AndroidStudio 开发前端,使用 Swift/ObjC/Xcode 完成后端
- java - BufferedReader 停止从 HttpURLConnection 读取大 Json 而没有错误
- android - Android:通过其他应用程序打开文件
- ios - 在 Swift 中使用 application/vnd.wfa.wsc 创建 NDEF WiFi 记录
- python - 文档说要使用置信度参数,但会引发错误
- youtube-api - 无法检索某些频道的 youtube 频道视频
- javascript - 多条主背景填充选项,覆盖加载条,如何解决?
- python - 如何在一个键下创建具有多个值的特殊字典?