我有一個非常簡單的標簽替換問題,我正在嘗試使用 BeatifulSoup 的replace_with方法來解決,但我無法理解它應該如何作業。我有字串'<b>This is text</b>',我想簡單地將其轉換為'<bold>This is text</bold>'. 似乎 bs4 的replace_with命令應該能夠做到這一點,但它并沒有像我期望的那樣作業。我嘗試了(在其他一些變體中)這樣的事情:
>>> a = '<b>This is text</b>'
>>> soup = BeautifulSoup(a, 'html.parser')
>>> new_tag = soup.new_tag('bold')
>>> soup.b.replace_with(new_tag)
<b>This is text</b>
>>> soup
<bold></bold>
如您所見,標簽已被替換,但隨后我丟失了文本。我可以用字串替換來做這種事情,但我真的很想理解為什么這不起作用,因為我傾向于在使用其他方法的 bs4 上遇到類似的問題,我必須在這里誤解一些基本的東西。
uj5u.com熱心網友回復:
隨著.replace_with您用新標簽替換整個標簽 - 新標簽沒有任何內容(文本)。請嘗試:
a = "<b>This is text</b>"
soup = BeautifulSoup(a, "html.parser")
soup.b.name = "bold"
print(soup)
印刷:
<bold>This is text</bold>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475032.html
標籤:Python python-3.x 美丽的汤
