Created
October 4, 2017 05:11
-
-
Save mrgarita/41417c41443de5fadb9488a7af49ee1f to your computer and use it in GitHub Desktop.
Python: HTMLタグ内の特定のタグのみを消去する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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