Beautifulsoup split text in tag by lt;br/gt;(Beautifulsoup 通过 lt;br/gt; 分割标签中的文本)
问题描述
是否可以通过 br 标签从标签中拆分文本?
Is it possible to split a text from a tag by br tags?
我有这个标签内容:[u'+420 777 593 531', <br/>, u'+420 776 593 531', <br/>, u'+420 775593 531']
我只想得到数字.有什么建议吗?
And I want to get only numbers. Any advices?
[x for x in dt.find_next_sibling('dd').contents if x!=' <br/>']
根本不工作.
推荐答案
您需要测试 标签,这些标签被建模为 Element 实例.Element 对象具有 name 属性,而文本元素没有(它们是 NavigableText 实例):
You need to test for tags, which are modelled as Element instances. Element objects have a name attribute, while text elements don't (which are NavigableText instances):
[x for x in dt.find_next_sibling('dd').contents if getattr(x, 'name', None) != 'br']
由于您在该 <dd> 元素中似乎只有文本和 <br/> 元素,因此您不妨只获取 所有包含的字符串 改为:
Since you appear to only have text and <br /> elements in that <dd> element, you may as well just get all the contained strings instead:
list(dt.find_next_sibling('dd').stripped_strings)
演示:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('''
... <dt>Term</dt>
... <dd>
... +420 777 593 531<br/>
... +420 776 593 531<br/>
... +420 775 593 531<br/>
... </dd>
... ''')
>>> dt = soup.dt
>>> [x for x in dt.find_next_sibling('dd').contents if getattr(x, 'name', None) != 'br']
[u'
+420 777 593 531', u'
+420 776 593 531', u'
+420 775 593 531', u'
']
>>> list(dt.find_next_sibling('dd').stripped_strings)
[u'+420 777 593 531', u'+420 776 593 531', u'+420 775 593 531']
这篇关于Beautifulsoup 通过 <br/> 分割标签中的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Beautifulsoup 通过 <br/> 分割标签中的文本
基础教程推荐
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 包装空间模型 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
