如何提取标签之间的所有文本?

3

我想从这本书中提取一首随机的诗歌。

使用BeautifulSoup,我已经找到了标题和散文。

print soup.find('div', class_="pre_poem").text
print soup.find('table', class_="poem").text

但是我想找到所有的诗歌并选择一首。我应该使用正则表达式匹配在<h3></span></p>之间的内容吗?


也许是 find_all() - furas
你知道这个项目吗:BoilerPipe - Antonio Ugraal Barile
永远不要使用正则表达式解析HTML。 - OneCricketeer
2个回答

0
假设您已经拥有了一个适当的对象可以使用,以下内容可能会帮助您入门:

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.

这是通过使用BeautifulSoup从每个元素中提取所有文本,直到找到下一个<h3>标签,然后删除任何额外的换行符来完成的。

0

使用HTML文档解析器。相比于正则表达式,它在意外后果方面更加安全。

所有程序员都不建议使用正则表达式解析HTML的原因是页面的HTML标记不是静态的,特别是如果您的源HTML是一个网页。正则表达式更适合字符串。

使用正则表达式需自负风险。


1
页面不是静态的这个论点实际上适用于任何你无法控制的数据解析。我认为更有说服力的论点是被解析的数据不是规则的。 - steinar
1
同意你的观点。赞一个! - Amen Jlili

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接