搜索

首页  >  问答  >  正文

提取多个没有类的span元素中的文本 - 使用BeautifulSoup

这就是HTML的样子:

<p class="details">
<span>detail1</span>
<span class="number">1</span>
<span>detail2</span>
<span>detail3</span>
</p>

我需要提取detail2和detail3。

但是使用这段代码,我只能得到detail1。

info = data.find("p", class_ = "details").span.text

我该如何提取所需的项目?

提前感谢!

P粉903052556P粉903052556444 天前955

全部回复(2)我来回复

  • P粉041856955

    P粉0418569552023-09-16 15:38:11

    在你的情况下,选择更具体的元素,即选择所有具有class为number的元素的兄弟元素:

    soup.select('span.number ~ span')

    示例

    from bs4 import BeautifulSoup
    html='''<p class="details">
    <span>detail1</span>
    <span class="number">1</span>
    <span>detail2</span>
    <span>detail3</span>
    </p>'''
    soup = BeautifulSoup(html)
    
    [t.text for t in soup.select('span.number ~ span')]

    输出

    ['detail2', 'detail3']

    回复
    0
  • P粉099145710

    P粉0991457102023-09-16 14:52:27

    您可以找到所有的 <span> 并进行普通索引:

    from bs4 import BeautifulSoup
    
    html_doc = """\
    <p class="details">
    <span>detail1</span>
    <span class="number">1</span>
    <span>detail2</span>
    <span>detail3</span>
    </p>"""
    
    soup = BeautifulSoup(html_doc, "html.parser")
    
    spans = soup.find("p", class_="details").find_all("span")
    
    for s in spans[-2:]:
        print(s.text)
    

    输出结果:

    detail2
    detail3
    

    或者使用 CSS 选择器:

    spans = soup.select(".details span:nth-last-of-type(-n+2)")
    
    for s in spans:
        print(s.text)
    

    输出结果:

    detail2
    detail3
    

    回复
    0
  • 取消回复