搜索

首页  >  问答  >  正文

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粉878510551597 天前601

全部回复(1)我来回复

  • P粉824889650

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

    你绝对可以使用BeautifulSoup来提取包含多个单词的HTML标签中的文本。在你的例子中,你想要从包含多个单词内容的<a>标签中提取文本。以下是使用Python中的BeautifulSoup实现这一目标的方法。

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    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
  • 取消回复