【发布时间】:2015-12-12 04:38:59
【问题描述】:
import urllib2,sys
from bs4 import BeautifulSoup,NavigableString
obama_4427_url = 'http://www.millercenter.org/president/obama/speeches/speech-4427'
obama_4427_html = urllib2.urlopen(obama_4427_url).read()
obama_4427_soup = BeautifulSoup(obama_4427_html)
# find the speech itself within the HTML
obama_4427_div = obama_4427_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})
# convert soup to string for easier processing
obama_4427_str = str(obama_4427_div)
# list of characters to be removed from obama_4427_str
remove_char = ['<br/>','</p>','</div>','<div class="indent" id="transcript">','<h2>','</h2>','<p>']
remove_char
for char in obama_4427_str:
if char in obama_4427_str:
obama_4427_replace = obama_4427_str.replace(remove_char,'')
obama_4427_replace = obama_4427_str.replace(remove_char,'')
print(obama_4427_replace)
使用BeautifulSoup,我从上述网站上抓取了奥巴马的一篇演讲。现在,我需要以有效的方式替换一些残留的 HTML。我在remove_char 中存储了我想消除的元素列表。我正在尝试编写一个简单的for 语句,但出现错误:TypeError: expected a character object buffer。这是一个初学者的问题,我知道,但我怎样才能解决这个问题?
【问题讨论】:
标签: python string list replace beautifulsoup