編集:基本的に、私は分解を実行しようとしていますが、タグを削除してその内容を完全に破棄するのではなく、タグをその内容に置き換えたいと思います。
HTMLドキュメントのすべての「a」タグを文字列形式のタグコンテンツに置き換えたいのですが。これにより、htmlをcsvに簡単に書き込むことができます。ただし、交換手順を通過できません。BeautifulSoupのreplace_with()を使用してそれを実行しようとしましたが、期待どおりの結果が得られません。
# Import modules
from bs4 import BeautifulSoup
from urllib2 import urlopen
# URL to soup
URL = 'http://www.barringtonhills-il.gov/foia/ordinances_12.htm'
html_content = urlopen(URL).read()
soup = BeautifulSoup(html_content)
# Replaces links with link text
links = soup.find_all('a')
for link in links:
linkText = link.contents[0]
linkTextCln = '%s' % (linkText.string)
if linkTextCln != 'None':
link.replaceWith(linkTextCln)
print link
これは次を返します:
<a href="index.htm">Home</a>
<a href="instruct.htm">Instructions</a>
<a href="requests.htm">FOIA Requests</a>
<a href="kiosk.htm">FOIA Kiosk</a>
<a href="geninfo.htm">Government Profile</a>
etc etc etc
しかし、期待収益は次のとおりです。
Home
Instructions
FOIA Requests
FOIA Kiosk
Government Profile
etc etc etc
replaceWithが期待どおりに機能しない理由について何か考えはありますか?この質問に対するより良いアプローチはありますか?