Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python BeautifulSoup XML, AttributeError: can't set attribute, How to set to text attribute?

My Xml code looks like this

<!-- ************************************************************************ -->
      <group title="Test procedure FBlock ablock">
        <case ident="Init" title="TS01 Activate" name="TC_Start_Application">
            <param name="Min" type="float">0.50
            </param>
            <param name="Max" type="float">5.00
            </param>
        </case>
      </group>

Now I can read the text attribute of 'param' in python with Beautiful soup library like this:

TTgroup = re.compile('Test someword (.*?): .*')

with open(outFile) as fp:
    soup = BeautifulSoup(fp, "lxml")

groups=soup.find_all("group")
for group in groups:
    FBlk = group["title"]
    FBlk=TTgroup.search(FBlk)

cases = group.find_all("case")
for case in cases:
    casetitle = case["title"]
    method=str(re.sub(r'TS.*? ', '',casetitle))
    Fkt=method.split('.') # split at .
    Fkt=str(Fkt[0]) # Function ID from case
    method=re.sub('[ (){}<># .,-]', '', method)# Remove unwanted characters
    method=method.replace('0x', 'x') # Replace 0x to x

    Params = case.find_all("param")
    for Param in Params:
        if Param["name"] =="Min":
            Param.text ="&"+Param["name"]+";<!--"+Param.text+"-->"

But,I am not able to change the text attribute of param, and getting this error message

Param.text ="&"+Param["name"]+";<!--"+Param.text+"-->"
AttributeError: can't set attribute
like image 332
Om Choudhary Avatar asked Jul 29 '26 01:07

Om Choudhary


1 Answers

The text attribute is read-only so you can't modify it, but you can modify the string attribute.
So you can change the Tag's text content if you replace .text,

Param.text ="&"+Param["name"]+";<!--"+Param.text+"-->"

with .string,

Param.string ="&"+Param["name"]+";<!--"+Param.text+"-->" 
like image 200
t.m.adam Avatar answered Jul 31 '26 18:07

t.m.adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!