Python BeautifulSoup 要素のモディファイについて¶
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
html = """<!-- SAMPLE -->
<a href="sample-A.html">sample-A</a>
<a href="sample-B.html">sample-B</a>"""
soup = BeautifulSoup(html, 'lxml')
# 比較のためにオリジナルの文字列表現を取っておく
soupOrgStr = str(soup)
# href の中身を other-domein/sample-*.html に書き換える
for a in soup.find_all('a') :
a['href'] = 'other-domein/' + a['href']
# ついでに target="_blank" を付け足す
a['target'] = "_blank"
# BeautifulSoup オブジェクトの文字列表現を見比べてみる
print("ORG:\n", soupOrgStr)
print("")
# soup の方は破壊的に変更されているのがわかる
print("modified:\n", str(soup))
実行結果: ORG: <!-- SAMPLE --><html><body><a href="sample-A.html">sample-A</a> <a href="sample-B.html">sample-B</a></body></html> modified: <!-- SAMPLE --><html><body><a href="other-domein/sample-A.html" target="_blank">sample-A</a> <a href="other-domein/sample-B.html" target="_blank">sample-B</a></body></html> 参考: Beautiful Soup Documentation > Quick Start > attributes
Last modified: 2016-12-19 | ||
|
||
|
|
||
| © Shin Nakamura/BasicWerk 2008 - 2025 |