To find the text of all "

" tags under a certain "" tag of the specified content in Python, you can use the "BeautifulSoup" library. Here's an example:

from bs4 import BeautifulSoup

# Example HTML content
content = \"""
<html>
  <body>
    <h1>Heading 1</h1>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <h2>Heading 2</h2>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
    <h3>Heading 3</h3>
    <p>Paragraph 5</p>
  </body>
</html>
"""

# Create BeautifulSoup object
soup = BeautifulSoup(content, 'html.parser')

# Find the desired <h> tag
heading = soup.find('h2')

# Find all <p> tags under the specified <h> tag
p_tags = heading.find_next_siblings('p')

# Extract the text from each <p> tag
p_texts = [p.get_text() for p in p_tags]

# Print the text of all <p> tags
for text in p_texts:
    print(text)

Output:

Paragraph 3
Paragraph 4

In this example, we first create a BeautifulSoup object by passing the HTML content and the parser type. Then, we use the .find() method to locate the desired "" tag (in this case, <h2>). Next, we use the .find_next_siblings() method to find all "

" tags that appear after the specified "" tag. Finally, we extract the text from each "

" tag using the .get_text() method and print the results.

Python BeautifulSoup: Extract Text from <p> Tags Under a Specific <h> Tag

原文地址: https://www.cveoy.top/t/topic/qc3w 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录