Study/Code
Python BeautifulSoup Html Tag 생성하기.
MJ_DL
2023. 5. 9. 08:56
여러 HTML 파일에 로고를 박아줘야하는 작업이 생김.
- 반복 처리를 위해 코드로 작업화.
생성된 tag 구조
--body
--div
--svg
--path
--path
from bs4 import BeautifulSoup
page = open('./test.html', 'rt', encoding='utf-8').read()
soup = BeautifulSoup(page, 'html.parser')
# style 태그의 내용변경.
soup.style.string = 'font-family: ff-clan-web-pro, "Helvetica Neue", Helvetica, sans-serif; font-weight: 400; font-size: 0.875em; line-height: 1.71429; *, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } body { margin: 0; padding: 0; } .logo { position: absolute; right: 160px; bottom: 35px; z-index: 1; width: 5%; }'
# 새로운 태그 생성
new_tag_1 = soup.new_tag("div", **{'class':'logo'})
new_tag_2 = soup.new_tag("svg", **{'xmlns': 'http://www.w3.org/2000/svg','width': '250','height': '75','viewBox': '0 0 1141 297','version': '1.1',})
new_tag_3 = soup.new_tag("path", **{'stroke':'none', 'fill':'#04439c', 'fill-rule':'evenodd'})
new_tag_4 = soup.new_tag("path", **{'stroke':'none', 'fill':'#e50717', 'fill-rule':'evenodd'})
soup.body.div.append(new_tag_1)
soup.body.div.div.append(new_tag_2)
soup.body.div.div.svg.append(new_tag_3)
soup.body.div.div.svg.append(new_tag_4)
html = soup.prettify('utf-8')
with open("./output.html", "wb") as file:
file.write(html)