【问题标题】:Python BeautifulSoup XML, AttributeError: can't set attribute, How to set to text attribute?Python BeautifulSoup XML,AttributeError:无法设置属性,如何设置为文本属性?
【发布时间】:2018-08-30 22:55:08
【问题描述】:

我的 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>

现在我可以在 python 中使用 Beautiful soup 库读取“param”的文本属性,如下所示:

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

【问题讨论】:

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


    【解决方案1】:

    text 属性是只读的,因此您无法修改它,但您可以修改 string 属性。
    所以如果替换.text就可以改变Tag的文字内容,

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

    .string

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

    【讨论】:

      猜你喜欢
      • 2015-02-08
      • 2017-07-17
      • 1970-01-01
      • 2014-08-09
      • 2022-10-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      相关资源
      最近更新 更多