首頁  >  問答  >  主體

BeautifulSoup選擇器:選擇包含多個單字的HTML元素

<p>有沒有辦法讓我使用BeautifulSoup來取得包含多個單字的標籤的文字? </p> <p>例如,如果我有以下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>...我只想取得<code>hello there what's up</code></p>
P粉878510551P粉878510551433 天前468

全部回覆(1)我來回復

  • P粉824889650

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

    你絕對可以使用BeautifulSoup來擷取包含多個單字的HTML標籤中的文字。在你的例子中,你想要從包含多個單字內容的<a>標籤中提取文字。以下是使用Python中的BeautifulSoup來實現這一目標的方法。

    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)

    回覆
    0
  • 取消回覆