Reputation: 5165
Im trying to check if the span tag has the string '~', if it does I want to replace it with '0'.
I've hundreds of span tags, I want to change the span.text value, as i want to copy the IF Statement to many places throughout my code, it wont work hard coding the var001 into the if statement.
How can i do this?
my code
span = soup.find("span", id="id001")
if span.text in ['~']:
span.text = 0
var001 = span.text
but this gives the error
AttributeError: can't set attribute
Upvotes: 0
Views: 347
Reputation: 84465
With bs4 4.7.1+ you can use :contains to identify the relevant tags and leverage string.replace_with
for the change in the .text
. The ~ needs escaping to differentiate it from the general sibling combinator
from bs4 import BeautifulSoup as bs
html = '''<span>some text ~ </span>
<span>some text</span>
<span>some ~ text</span>
<span>some text</span>
<span>~ some text</span>'''
soup = bs(html, 'lxml')
for t in soup.select('span:contains(\~)'):
t.string.replace_with('0')
print(soup)
Upvotes: 1