Python BeautifulSoup XML,AttributeError:无法设置属性,如何设置为text属性?

时间:2018-03-21 17:20:28

标签: xml python-3.x beautifulsoup xml-parsing entity

我的Xml代码如下所示

<!-- ************************************************************************ -->
      <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>

现在我可以阅读&#39; param&#39;的文本属性了。在python中有这样美丽的汤库:

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+"-->"

但是,我无法更改param的text属性,并收到此错误消息

Param.text ="&"+Param["name"]+";<!--"+Param.text+"-->"
AttributeError: can't set attribute

1 个答案:

答案 0 :(得分:1)

text属性为只读,因此您无法对其进行修改,但您可以修改string属性。
因此,如果您替换Tag

,则可以更改.text的文字内容
Param.text ="&"+Param["name"]+";<!--"+Param.text+"-->"

.string

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