Home  >  Q&A  >  body text

BeautifulSoup selector: select HTML elements containing multiple words

<p>Is there a way for me to use BeautifulSoup to get the text of a label that contains multiple words? </p> <p>For example, if I have the following HTML: </p> <pre class="brush:php;toolbar:false;"><div> <div> <a>hello there</a> <a>hi</a> </div> <a>what's up</a> <a>stackoverflow</a> </div></pre> <p>...I just want to get<code>hello there what's up</code></p>
P粉878510551P粉878510551433 days ago467

reply all(1)I'll reply

  • P粉824889650

    P粉8248896502023-08-14 13:21:33

    You can definitely use BeautifulSoup to extract text from HTML tags that contain multiple words. In your example, you want to extract text from <a> tags that contain multi-word content. Here's how to achieve this using BeautifulSoup in Python.

    from bs4 import BeautifulSoup
    
    html = '''
    <div>
        <div>
            <a>hello there</a>
            <a>hi</a>
        </div>
        <a>what's up</a>
        <a>stackoverflow</a>
    </div>
    '''
    
    soup = BeautifulSoup(html, 'html.parser')
    
    target_tags = soup.find_all('a')  # 找到所有的<a>标签
    multi_word_texts = []
    
    for tag in target_tags:
        if ' ' in tag.get_text():  # 检查标签文本是否包含空格(表示多个单词)
            multi_word_texts.append(tag.get_text())
    
    result = ' '.join(multi_word_texts)
    print(result)

    reply
    0
  • Cancelreply