python - How do I modify strings generated by an element.strings method in BeautifulSoup? -


when there tags within other tags (e.g., <b> within <p>), string element of parent element empty, , strings element generator produces strings.

<html> <body> <p> first p <b> first b </b>second part first p</p> <p> second p <a> first link</a> second part second p <a> second link</a> third part second p</p>  </body> </html> 

in code,

soup = beautifulsoup(html)#text above ps = soup.find_all('p') p0 = ps[0] s in p0.strings:     #makes sure child elements inside <p> tag skipped     if s.findparent() == p0:         s.replace_with('new text') 

however, when run this,

traceback (most recent call last):       file "<pyshell#243>", line 1, in <module>         s.replace_with('new_text')       file "/usr/lib/python2.7/dist-packages/bs4/element.py", line 211, in replace_with         my_index = self.parent.index(self)     attributeerror: 'nonetype' object has no attribute 'index' 

the first string of p0 had text changed, last element did not, since error thrown. same thing happens second element of p1 = ps[1]. how go modifying each of string elements separately? want preserve of existing tags.

this loop not safe because modifying p0 iterate on it

for s in p0.strings: 

one safe way make list snapshot p0 before iterate on it.

for s in list(p0.strings): 

Comments

Popular posts from this blog

android - net_scheduler holding wakelock -

sql - MySQL : Getting Entries from a many-to-many table -

java - Retrieving data from database using jsp (Hibernate + Spring + Maven) -