亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python Beautiful Soup - 刪除的標簽仍然影響輸出

Python Beautiful Soup - 刪除的標簽仍然影響輸出

侃侃爾雅 2023-07-11 15:38:06
你好,from bs4 import BeautifulSouphtml = '<p>This <i>is</i> a test.</p>'soup = BeautifulSoup(html, 'lxml')print(soup)for tag in soup.find_all('i'):    tag.replace_with('is')print(soup)print("\n")print(soup.prettify())print("\n")for string in soup.stripped_strings:    print(string)該程序輸出以下內容:<html><body><p>This <i>is</i> a test.</p></body></html><html><body><p>This is a test.</p></body></html><html> <body>  <p>   This   is   a test.  </p> </body></html>Thisisa test為什么呢?為什么字符串仍然分為三部分,就好像刪除的標簽仍然存在一樣?如果我使用<p>This is a test.</p>(這是我替換標簽后的輸出)作為我的起始 html,一切都工作正常。我究竟做錯了什么?提前致謝
查看完整描述

1 回答

?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

看起來它替換<i>is</i>為is,但它沒有替換樹中的節點,并且它仍然is作為樹中的單獨項目運行。


您必須將樹轉換為字符串并再次解析它才能將其作為樹中的單個節點。


html = str(soup)

#print(html)

soup = BeautifulSoup(html, 'lxml')

如果您希望文本作為一個字符串那么您可以嘗試get_text(strip=True, separator=" ")


from bs4 import BeautifulSoup


html = '<p>This <i>is</i> a test.</p>'

soup = BeautifulSoup(html, 'lxml')


print(soup.get_text(strip=True, separator=" "))


查看完整回答
反對 回復 2023-07-11
  • 1 回答
  • 0 關注
  • 131 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號