简体   繁体   中英

Beautifulsoup split text in tag by <br/>

Is it possible to split a text from a tag by br tags?

I have this tag contents: [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?

EDIT:

[x for x in dt.find_next_sibling('dd').contents if x!=' <br/>']

Does not work at all.

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']

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)

Demo:

>>> 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']

Using get_text(strip=True, separator='\\n') with str.splitlines :

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>
''', 'html.parser')
print(soup.dd.get_text(strip=True, separator='\n').splitlines())
# ['+420 777 593 531', '+420 776 593 531', '+420 775 593 531']
tag =  BeautifulSoup('''
<dd>
    +420 777 593 531<br/>
    +420 776 593 531<br/>
    +420 775 593 531<br/>
</dd>
''', 'html.parser')

Convert this to a string

str_tag = str(tag)

Now split using <br/> tag and convert back to BeautifulSoup and extract text from it

numbers = [BeautifulSoup(_,'html.parser').text.strip() for _ in str(soup).split('<br/>')]
# output : ['+420 777 593 531', '+420 776 593 531', '+420 775 593 531', '']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM