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

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

BeautifulSoup 保留一些文本,但刪除標簽的其余部分

BeautifulSoup 保留一些文本,但刪除標簽的其余部分

喵喔喔 2023-07-11 16:14:43
我正在使用一個從論壇抓取數據的機器人。我這里有這個可以使用:<description><![CDATA[ <p>This is a test post with a few emotes <img src="https://sjc5.discourse-cdn.com/try/images/emoji/twitter/grin.png?v=9" title=":grin:" class="emoji" alt=":grin:"> <img src="https://sjc5.discourse-cdn.com/try/images/emoji/twitter/heart.png?v=9" title=":heart:" class="emoji" alt=":heart:"></p> ]]></description>從此我想得到This is a test post with a few emotes :grin: :heart:我該怎么做呢?如果表情也位于文本中間,我也希望能夠做到這一點。
查看完整描述

1 回答

?
青春有我

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

from bs4 import BeautifulSoup, CData


txt = '''<description><![CDATA[ <p>This is a test post with a few emotes <img src="https://sjc5.discourse-cdn.com/try/images/emoji/twitter/grin.png?v=9" title=":grin:" class="emoji" alt=":grin:"> <img src="https://sjc5.discourse-cdn.com/try/images/emoji/twitter/heart.png?v=9" title=":heart:" class="emoji" alt=":heart:"></p> ]]></description>'''


# load main soup:

soup = BeautifulSoup(txt, 'html.parser')


# find CDATA inside <description>, make new soup

soup2 = BeautifulSoup(soup.find('description').find(text=lambda t: isinstance(t, CData)), 'html.parser')


# replace <img> with their alt=...

for img in soup2.select('img'):

    img.replace_with(img['alt'])


# print text

print(soup2.p.text)

印刷:


This is a test post with a few emotes :grin: :heart:


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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