Skip to content

Instantly share code, notes, and snippets.

@mrgarita
Created October 4, 2017 05:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrgarita/41417c41443de5fadb9488a7af49ee1f to your computer and use it in GitHub Desktop.
Save mrgarita/41417c41443de5fadb9488a7af49ee1f to your computer and use it in GitHub Desktop.
Python: HTMLタグ内の特定のタグのみを消去する
# -*- coding: utf-8 -*-
import re # 正規表現のマッチ関数(match, findall...等)を使うため
# HTMLタグイメージ
html = """
<p>プログラミング学習<a href="http://diannao.work/">こちら</a></p>
<p>暇つぶし<a href="https://youtube.com/">こっち</a></p>
"""
# aタグの正規表現(<a href="****">XXXX</a>)
regexp = re.compile("<a.*/a>")
# htmlからaタグ部分のみを取り出す
atags = regexp.findall(html) # この時点でatagsには、
# <a href="http://diannao.work/">こちら</a>
# <a href="https://youtube.com/">こっち</a>
# の2つのaタグがリスト形式で格納されている
# htmlからaタグ部分をreplaceにより消去
for atag in atags:
html = html.replace(atag, "")
# aタグを取り除いたあとのhtmlを表示
print(html)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment