2012-12-02 11 views
4

나는 beautifulsoup를 사용하여 HTML을 구문 분석하려고하지만 인라인 스크립트 태그가있는 페이지를 방문 할 때마다 beautifulsoup이 내용을 인코딩하지만 마지막에는 다시 디코딩하지 않습니다. beautifulsoup 만드는 방법 스크립트 태그의 내용을 인코딩 및 디코딩

from bs4 import BeautifulSoup 

if __name__ == '__main__': 

    htmlData = '<html> <head> <script type="text/javascript"> console.log("< < not able to write these & also these >> "); </script> </head> <body> <div> start of div </div> </body> </html>' 
    soup = BeautifulSoup(htmlData) 
    #... using BeautifulSoup ... 
    print(soup.prettify()) 

내가이 출력하려면 :

<html> 
<head> 
    <script type="text/javascript"> 
    console.log("< < not able to write these & also these >> "); 
    </script> 
</head> 
<body> 
    <div> 
    start of div 
    </div> 
</body> 
</html> 

을하지만이 출력 얻을 :

<html> 
<head> 
    <script type="text/javascript"> 
    console.log("&lt; &lt; not able to write these &amp; also these &gt;&gt; "); 
    </script> 
</head> 
<body> 
    <div> 
    start of div 
    </div> 
</body> 
</html> 
+0

가 [제출 버그]이 (https://bugs.launchpad.net/beautifulsoup/+bug/950459)에 대한 Beautiful Soup 3. 버그가 Beautiful Soup에서 지속되는 것처럼 보입니다. 4. 버그 신고서 [https://bugs.launchpad.net/beautifulsoup/]를 원할 수 있습니다. –

답변

-1

당신은 이런 일을 할 수있는을

내가 사용하는 코드입니다 :

htmlCodes = (
('&', '&amp;'), 
('<', '&lt;'), 
('>', '&gt;'), 
('"', '&quot;'), 
("'", '&#39;'), 
) 

for i in htmlCodes: 
    soup.prettify().replace(i[1], i[0]) 
+1

-1. 이것에 많은 잘못이있다. 우선, 각 반복마다 prettify를 호출하여 이전 대체 결과를 삭제합니다. 둘째, 자바 스크립트 부분에없는 모든 문자 엔티티 참조를 clobber. –

1

당신은 lxml을 시도 할 수 있습니다 :

import lxml.html as LH 

if __name__ == '__main__': 
    htmlData = '<html> <head> <script type="text/javascript"> console.log("< < not able to write these & also these >> "); </script> </head> <body> <div> start of div </div> </body> </html>' 
    doc = LH.fromstring(htmlData) 
    print(LH.tostring(doc, pretty_print = True)) 

가 산출

<html> 
<head><script type="text/javascript"> console.log("< < not able to write these & also these >> "); </script></head> 
<body> <div> start of div </div> </body> 
</html>