Beautifulsoup 通过 <br/> 分割标签中的文本
问题描述
是否可以通过 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']
相关文章