使用 Beautiful Soup python 添加或更新标签中的属性

问题描述 投票:0回答:1
python beautifulsoup html-escape-characters
1个回答
0
投票

soup
在您执行
tag['key'] = key
时更新,因此无需执行字符串替换 — beautifulsoup 设计为您只需直接对 BeautifulSoup 对象进行更改,然后在最后导出更新的字符串。

这也使代码更短。由于您没有提供

generate_key_from_name
函数,我刚刚为下面的代码创建了一个始终返回
"Reporter's name"
的虚拟函数。

def generate_key_from_name(input_str):

    return "Reporter's name"


html_code = '<table id="definition-table"><tbody><tr><td>' \
            '<p><b><i><span class="lang">*Reporter&#39;s name:</span></i></b></p>' \
            '</td><td>John Doe</td></tr></tbody></table>'
soup = BeautifulSoup(html_code, "html.parser")
for tag in soup.findAll("span", {"class": "lang"}):
    key = generate_key_from_name(tag.string)
    tag['key'] = key
str(soup)

输出:

'<table id="definition-table"><tbody><tr><td><p><b><i><span class="lang" key="Reporter\'s name">*Reporter\'s name:</span></i></b></p></td><td>John Doe</td></tr></tbody></table>'

或者你可以调用

soup.prettify()
而不是
str(soup)
得到:

<table id="definition-table">
 <tbody>
  <tr>
   <td>
    <p>
     <b>
      <i>
       <span class="lang" key="Reporter's name">
        *Reporter's name:
       </span>
      </i>
     </b>
    </p>
   </td>
   <td>
    John Doe
   </td>
  </tr>
 </tbody>
</table>

希望这对您有所帮助——如果我遗漏了什么,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.