반응형
text = """<div>
<h1>Title</h1>
<p>A long text........ </p>
<a href=""> a link </a>
</div>"""

이러한 string 텍스트가 있을때 string 내의 html 태그를 지우고 싶을떄가 있다.

두가지 방법을 이용할 수 있다.

 

1. 정규표현식  (regex)

import re

def cleanhtml(raw_html):
  cleanr = re.compile('<.*?>')
  cleantext = re.sub(cleanr, '', raw_html)
  return cleantext

만약 &nsbm 가 포함된 string 이라면

import re

def cleanhtml(raw_html):
  cleanr = re.compile('<.*?>|&([a-z0-9]+|#[0-9]{1,6}|#x[0-9a-f]{1,6});')
  cleantext = re.sub(cleanr, '', raw_html)
  return cleantext

 

2. BeautifulSoup 

from bs4 import BeautifulSoup
cleantext = BeautifulSoup(raw_html, "lxml").text

 

 

외부라이브러리를 사용하는것을 지양한다면 1번안을 사용하나

text의 길이가 매우 큰 경우에는 속도적인 면에서는 2번안이 더 좋다.

반응형

+ Recent posts