2014-12-01 4 views
6

나는 HTML 파일 모음을 가지고 있습니다. 특정 클래스의 마크 업을 편집하여 하나씩 반복하고 싶습니다. 항상 같은이 대신 "다른 곳에서 저를 넣어"의 다른 텍스트와 같은 문서에 여러 번 발생할 수 있습니다한 종류의 태그를 BeautifulSoup의 다른 태그로 바꾸기

<td class='thisIsMyClass' colspan=4> 
    <a id='123' class='thisIsMyOtherClass' href='123'>Put me Elsewhere</a> 

:하지만, 내가 편집하고자하는 코드는 다음 클래스 이름을 사용하여, 다음과 같은 형식이다 수업.

나는이 같은 형태로 변경하려는

: 너무 확실

<font SIZE="3" COLOR="#333333" FACE="Verdana" STYLE="background-color:#ffffff;font-weight: bold;"> 
    <h2>Put Me Elsewhere</h2> 
</font> 
import os 
for filename in os.listdir('dirname'): 
replace(filename) 

def replace(filename): 
tags = soup.find_all(attrs={"thisIsMyClass"}) 

하지 곳 후 이동하는 방법 또는 태그 배열로 처리? 어떤 도움이라도 대단히 감사 할 것입니다. 감사합니다 :)

+0

HTML에는

개 요소의 어린이가 일부 제한 사항이 있습니다. 태그 만 바꾸는 것이 좋습니다. 그들의 속성으로 인해
을 지워야 할 필요가 있다면, 보통 으로 대체하는 것이 그것들을 모두 지우는 것보다 낫습니다. – tiffon

답변

4

훨씬 더 thisIsMyClass 클래스 모든 td 태그를 찾아 자리 표시 자로 대체 HTML 문자열을 준비하고 각 교체 .replace_with()을 사용하는 것입니다 더 아름다운 :

from bs4 import BeautifulSoup 

data = """ 
<table> 
    <tr> 
     <td class='thisIsMyClass' colspan=4> 
      <a id='123' class='thisIsMyOtherClass' href='123'>Put me Elsewhere</a> 
     </td> 
    </tr> 
</table> 
""" 

replacement = """ 
<font SIZE="3" COLOR="#333333" FACE="Verdana" STYLE="background-color:#ffffff;font-weight: bold;"> 
    <h2>{text}</h2> 
</font> 
""" 

soup = BeautifulSoup(data, 'html.parser') 
for td in soup.select('td.thisIsMyClass'): 
    td.replace_with(BeautifulSoup(replacement.format(text=td.a.text), 'html.parser')) 

print soup.prettify() 

인쇄 :

<table> 
    <tr> 
     <font color="#333333" face="Verdana" size="3" style="background-color:#ffffff;font-weight: bold;"> 
      <h2> 
      Put me Elsewhere 
      </h2> 
     </font> 
    </tr> 
</table> 
1

이것은 name 속성에 지정하는 것처럼 간단합니다.

# for quick testing: 
# tag = BeautifulSoup("<td class='thisIsMyClass' colspan=4><a id='123' class='thisIsMyOtherClass' href='123'>Put me Elsewhere</a>") 
# tags = [tag] 
for tag in tags: 
    tag.td.name = "font" 
    tag.font["SIZE"] = 3 
    del tag.font["class"] 
    ... 
    tag.a.name = "h2" 
    ... 
    print(tag) 
    # <font SIZE="3" colspan="4"><h2 class="thisIsMyOtherClass" href="123" id="123">Put me Elsewhere</h2></font> 

또한 documentation은 (는) 친구입니다. 꽤 포괄적입니다.

관련 문제