Beautifulsoup在标签中用< br/>分割了文本 [英] Beautifulsoup split text in tag by <br/>
本文介绍了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 775 593 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'\n +420 777 593 531', u'\n +420 776 593 531', u'\n +420 775 593 531', u'\n']
>>> 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/>分割了文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文