【问题标题】:Is there a function in Beautiful soup that allows you to find the index of a specific <p> tagBeautiful Soup 中是否有一个功能可以让您找到特定 <p> 标记的索引
【发布时间】:2021-07-22 00:43:29
【问题描述】:

我想获取打击乐列表中第一个对象的&lt;p&gt; 标签的索引。怎么做呢?

from bs4 import BeautifulSoup
import re


data = '''
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Instruments</title>
</head>
<body>
    <p> Guitars are string instruments </p>
    <p> Saxophones are woodwind instruments </p>
    <p> Drums are percussion instruments </p>
    <p> Pianos are percussion instruments</p>
</body>
'''

soup = BeautifulSoup(data)
pattern = '(?=.*percussion).*'
percussion = soup.findAll(string=re.compile(pattern))
print(percussion[0].parent.name]

【问题讨论】:

    标签: python html indexing beautifulsoup tags


    【解决方案1】:

    使用.index 方法。例如:

    from bs4 import BeautifulSoup
    
    
    data = """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Instruments</title>
    </head>
    <body>
        <p> Guitars are string instruments </p>
        <p> Saxophones are woodwind instruments </p>
        <p> Drums are percussion instruments </p>
        <p> Pianos are percussion instruments</p>
    </body>
    """
    
    soup = BeautifulSoup(data, "html.parser")
    
    percussion_p = soup.find("p", text=lambda t: "percussion" in t)
    all_p = soup.find_all("p")
    
    print('Index of <p> with text "percussion" is:', all_p.index(percussion_p))
    

    打印(0-indexed):

    Index of <p> with text "percussion" is: 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-06
      • 2019-11-23
      • 1970-01-01
      • 1970-01-01
      • 2018-02-09
      • 1970-01-01
      • 2012-10-23
      • 2015-05-19
      相关资源
      最近更新 更多