我想从这本书中提取一首随机的诗歌。
使用BeautifulSoup,我已经找到了标题和散文。
print soup.find('div', class_="pre_poem").text
print soup.find('table', class_="poem").text
但是我想找到所有的诗歌并选择一首。我应该使用正则表达式匹配在<h3>
和</span></p>
之间的内容吗?
我想从这本书中提取一首随机的诗歌。
使用BeautifulSoup,我已经找到了标题和散文。
print soup.find('div', class_="pre_poem").text
print soup.find('table', class_="poem").text
但是我想找到所有的诗歌并选择一首。我应该使用正则表达式匹配在<h3>
和</span></p>
之间的内容吗?
poem_ids = []
for section in soup.find_all('ol', class_="TOC"):
poem_ids.extend(li.find('a').get('href') for li in section.find_all('li'))
poem_ids = [id[1:] for id in poem_ids[:-1] if id]
poem_id = random.choice(poem_ids)
poem_start = soup.find('a', id=poem_id)
poem = poem_start.find_next()
poem_text = []
while True:
poem = poem.next_element
if poem.name == 'h3':
break
if poem.name == None:
poem_text.append(poem.string)
print '\n'.join(poem_text).replace('\n\n\n', '\n')
首先从页面顶部的目录中提取诗歌列表。每首诗都包含唯一的ID。然后选择一个随机ID,并基于该ID提取相应的诗歌。
例如,如果选择了第一首诗,将会看到以下输出:
"The Arrow and the Song," by Longfellow (1807-82), is placed first in
this volume out of respect to a little girl of six years who used to
love to recite it to me. She knew many poems, but this was her
favourite.
I shot an arrow into the air,
It fell to earth, I knew not where;
For, so swiftly it flew, the sight
Could not follow it in its flight.
I breathed a song into the air,
It fell to earth, I knew not where;
For who has sight so keen and strong
That it can follow the flight of song?
Long, long afterward, in an oak
I found the arrow, still unbroke;
And the song, from beginning to end,
I found again in the heart of a friend.
Henry W. Longfellow.
<h3>
标签,然后删除任何额外的换行符来完成的。使用HTML文档解析器。相比于正则表达式,它在意外后果方面更加安全。
所有程序员都不建议使用正则表达式解析HTML的原因是页面的HTML标记不是静态的,特别是如果您的源HTML是一个网页。正则表达式更适合字符串。
使用正则表达式需自负风险。
find_all()
? - furas