2013-05-12 3 views
0

html 페이지의 내용과 문자열을 비교하고 싶습니다. 그러나 HTML 페이지의 특수 문자는이 비교를 더 어렵게 만듭니다. 그래서 비교하기 전에 HTML 페이지에서 모든 특수 문자와 공백을 제거하고 싶습니다. 그러나 모든 태그는 동일하게 유지되어야합니다. 는 BeautifulSoup 태그 내용의 특수 문자 제거

<div class="abc bcd"> 
     <div class="inner1"> Hai ! this is first inner div;</div> 
     <div class="inner2"> "this is second div... " </div> 
</div> 

는 어떻게이 작업을 수행 할 수 있습니다

<div class="abc bcd"> 
      <div class="inner1">Haithisisfirstinnerdiv</div> 
      <div class="inner2">thisisseconddiv</div> 
</div> 

로 변환해야된다?

+0

텍스트를 BeautifulSoup로 바꾸는 방법을 설명합니다. – Blender

답변

0

모든 리프 태그를 찾아 문자열을 변경하십시오. 여기에 방법입니다

<div class="inner1"> 

<div class="inner1"> 

가 간다 :

alphabet = 'abcdefghijklmnopqrtsuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' 

def replace(soup): 
    for child in soup.children: 
     if child.string: 
      child.string = ''.join([ch for ch in child.string if ch in alphabet]) 
     else: 
      replace(child) 

from bs4 import BeautifulSoup 

orig_string = """ 
<div class="abc bcd"> 
     <div class="inner1"> Hai ! this is first inner div;</div> 
     <div class="inner2"> "this is second div... " </div> 
</div> """ 

soup = BeautifulSoup(orig_string) 
print soup.prettify() # original HTML 
replace(soup) 
print 
print soup.prettify() # new HTML 

는 출력 : 그래서 BeautifulSoup()를 호출 할 때 해제

<html> 
<body> 
    <div class="abc bcd"> 
    <div class="inner1"> 
    Hai ! this is first inner div; 
    </div> 
    <div class="inner2"> 
    "this is second div... " 
    </div> 
    </div> 
</body> 
</html> 

<html> 
<body> 
    <div class="abc bcd"> 
    <div class="inner1"> 
    Haithisisfirstinnerdiv 
    </div> 
    <div class="inner2"> 
    thisisseconddiv 
    </div> 
    </div> 
</body> 
</html> 
+1

그냥 작은 일,'import string; string.letters'는 소문자와 대문자 모두 알파벳을 생성합니다. – TerryA

+0

유니 코드 인식을 위해 모든 문자를 열거하지 마십시오. 대신에'unicodedata'를 가져오고'ch에서 알파벳 '대신'unicodedata.category (ch) [0] =='L ''을 사용하십시오. – icktoofay

+0

또한,'child = replace (child) '의'child ='는 쓸모가 없습니다. – icktoofay

0

첫째, BeautifulSoup 이미 일부 깨진 HTML을 수정 ~을 얻다 공백 및 특수 문자 제거 :

>>> from bs4 import BeautifulSoup 
>>> html = """<div class="abc bcd"> 
    <div class="inner1"> Hai ! this is first inner div;</div> 
    <div class="inner2"> "this is second div... " </div> 
</div>""" 
>>> soup = BeautifulSoup(html) 
>>> for divtag in soup.findAll('div'): 
...  if 'inner' in divtag['class'][0]: 
...   divtag.string = ''.join(i for i in divtag.string if i.isalnum()) 
>>> print soup 
<html><body><div class="abc bcd"> 
<div class="inner1">Haithisisfirstinnerdiv</div> 
<div class="inner2">thisisseconddiv</div> 
</div></body></html>