可以使用BeautifulSoup從HTML中刪除腳本標記及其所有內容,還是必須使用正則表達式或其他內容?我可以使用BeautifulSoup刪除腳本標籤嗎?
56
A
回答
110
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<script>a</script>baba<script>b</script>', 'lxml')
>>> [s.extract() for s in soup('script')]
>>> soup
baba
12
如(official documentation)說,你可以使用extract
方法來刪除所有搜索匹配的子樹。
import BeautifulSoup
a = BeautifulSoup.BeautifulSoup("<html><body><script>aaa</script></body></html>")
[x.extract() for x in a.findAll('script')]
10
更新答案爲那些誰可能需要以供將來參考: 正確的答案是。 decompose()
您可以使用不同的方式,但decompose
就地工作。
用法示例:
soup = BeautifulSoup('<p>This is a slimy text and <i> I am slimer</i></p>')
soup.i.decompose()
print str(soup)
#prints '<p>This is a slimy text and</p>'
非常有用擺脫碎屑像「腳本」,「IMG」,所以,等等。
相關問題
- 1. 我們可以通過腳本刪除HTML5 Canvas標籤的「getContext」屬性嗎?
- 2. 我可以刪除其他人簽名的標籤嗎?
- 3. 我可以在JQuery中刪除幾個HTML標籤嗎?
- 4. 從BeautifulSoup對象中刪除標籤
- 5. 從BeautifulSoup解析HTML中刪除標籤
- 6. BeautifulSoup - 刪除MS Word特定標籤?
- 7. BeautifulSoup標籤去除
- 8. 我可以刪除flashlogs.txt嗎?
- 9. 我可以刪除xxxxxxxAreaRegistration.cs嗎?
- 10. 我們可以刪除/清除以前設置的標籤到視圖嗎?
- 11. 我可以在動態腳本標籤插入中使用Facebook Javascript SKD嗎?
- 12. 我可以使用Blogger條件標籤(IF)在Java腳本
- 13. 我可以在SVG標籤內使用HTML標籤嗎?
- 14. 我可以用css輸入標籤嗎?
- 15. 從文本文件中刪除BeautifulSoup標籤
- 16. 使用BeautifulSoup獲取HTML文件的腳本和樣式標籤?
- 17. 如何通過腳本標籤使用python解析和beautifulsoup
- 18. 使用bash腳本添加/刪除xml標籤
- 19. Python beautifulsoup刪除自我關閉標記
- 20. 你可以添加和刪除部分標籤嗎?基礎HTML
- 21. 可以在HTML5的頁腳標籤中使用章節標籤嗎?
- 22. 使用BeautifulSoup拉標籤值
- 23. 使用自閉DIV標籤可以嗎?
- 24. 這會刪除所有可能的腳本標記嗎?
- 25. 使用WhirlyGlobe刪除標籤
- 26. 我可以使用其用戶UID刪除FIRAuth用戶嗎?
- 27. Rails_admin刪除可選標籤
- 28. 我可以修改此腳本以使用多個DIV標記嗎?
- 29. 我可以刪除這些跨度嗎?
- 30. 我們可以刪除dom表嗎?
什麼是鏈接附加標籤被刪除的最佳方式?現在,如果我一個接一個地重複命令,用[s.extract()for s in soup('script')],然後[s.extract()for s in soup('iframe')]等, ,但如果我把它們鏈接起來就像[s.extract()for s in soup('iframe','script')]。 – Ila 2012-10-18 15:47:43
@Ali你將不得不使用'[s.extract()for s in soup(['iframe','script'])]'請注意,要使用多個標籤,參數必須是列表 – 2012-10-18 19:10:50
@FábioDiniz我提取了如下內容:'' baba ''?它是一樣的嗎? – user2883071 2015-04-29 18:03:17