Need Help with the BeautifulSoup problem, please

Andreas Perstinger andipersti at gmail.com
Mon Dec 16 04:32:10 EST 2013


On 16.12.2013 07:41, seaspeak at gmail.com wrote:
> I need to replace all tag <b> with <span> after ■. But the result
> frombelow is '■ <span style="REPLACE">D</span> / <font></font>'
> Can you explain what I did wrong, please.
>
>      s = '■<b>A</b> <b>B</b> <b>C</b> <b>D</b> / <font></font>'
>      soup = BeautifulSoup(s)
>      for i in soup.find_all(text='■'):
>          tag = soup.new_tag('span')
>          tag['style'] = 'REPLACE'
>          for ii in i.find_next_siblings():
>              if ii.name=='font' or str(ii).lstrip('')[0:1]=='/':
>                  break
>              else:
>                  if ii.name=='b':
>                      tag.string=ii.string
>                      print(ii.replace_with(tag))
>      print(soup)
>

You are only creating one new tag but as I understand your problem you 
want to replace each b-element with a new tag. Simply move the tag 
creating part:

for i in soup.find_all(text='■'):
     for ii in i.find_next_siblings():
         if ii.name=='font' or str(ii).lstrip('')[0:1]=='/':
             break
         else:
             if ii.name=='b':
                 tag = soup.new_tag('span')
                 tag['style'] = 'REPLACE'
                 tag.string=ii.string
                 print(ii.replace_with(tag))

And please read
https://wiki.python.org/moin/GoogleGroupsPython
if you want to continue using Google Groups for accessing this list.

Bye, Andreas



More information about the Python-list mailing list