BeautifulSoup selector: select HTML elements containing multiple words
P粉878510551
P粉878510551 2023-08-13 19:25:41
0
1
509
<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粉878510551
P粉878510551

reply all(1)
P粉824889650

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)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template