Python BeautifulSoup: Extract Text from <p> Tags Under a Specific <h> Tag
To find the text of all "
" tags under a certain "
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 " tags that appear after the specified " " tag using the .find() method to locate the desired "<h2>). Next, we use the .find_next_siblings() method to find all ".get_text() method and print the results.
原文地址: https://www.cveoy.top/t/topic/qc3w 著作权归作者所有。请勿转载和采集!