beautifulsoup在两个标签之间提取文本

时间:2018-01-11 03:43:22

标签: python python-3.x beautifulsoup

我有这个HTML代码段:

<h3>Language</h3>
    <a class="syllabus-item" href="">French</a>
    <a class="syllabus-item" href="">English</a>
    <a class="syllabus-item" href="">Spanish</a>

<h3>Music</h3>
    <a class="syllabus-item" href="">Rock</a>
    <a class="syllabus-item" href="">Pop</a>

我希望输出为:

1 - Language/1 - French
1 - Language/2 - English
1 - Language/3 - Spanish
2 - Music/1 - Rock
2 - Music/2 -Pop

这是我的代码

def get_genre_band(soup):
    genre = None
    for node in soup.findAll(['h3', 'a']):
        if node.name == 'h3':
            genre = node.text
        elif 'syllabus-item' in node.get('class', ''):
            yield genre.strip(), node.text.strip()

我正在使用它:

            for g, b in get_genre_band(section):
            print("{} \n\t{}".format(g, b))

但我无法得到正确的数字,我得到这样的东西:

1 - Language/1 - French
1 - Language/2 - English
1 - Language/3 - Spanish
8 - Music/4 - Rock
9 - Music/5 -Pop

1 个答案:

答案 0 :(得分:1)

您可以使用.next_sibling执行此任务。

<强>代码:

for i, header in enumerate(soup.find_all('h3'), 1):
    next_tag = header
    j = 1
    while True:
        next_tag = next_tag.next_sibling
        if next_tag is None or next_tag.name == 'h3':
            break
        if next_tag.name is not None:
            print('{} - {}/{} - {}'.format(i, header.text, j, next_tag.string))
            j += 1

<强>输出:

1 - Language/1 - French
1 - Language/2 - English
1 - Language/3 - Spanish
2 - Music/1 - Rock
2 - Music/2 - Pop