Python BeautifulSoup: Extract Text from <p> Tags Under <h> Tag
To find the text of all '
' tags under the '
from bs4 import BeautifulSoup
# Assuming the specified content is stored in a variable called 'content'
# Parse the content using BeautifulSoup
soup = BeautifulSoup(content, 'html.parser')
# Find the <h> tag
h_tag = soup.find('h')
# Find all <p> tags under the <h> tag
p_tags = h_tag.find_all('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 p_text in p_texts:
print(p_text)
Make sure you have installed the 'beautifulsoup4' package before running the code (you can install it using pip install beautifulsoup4). Replace the variable 'content' with your actual HTML content.
原文地址: https://www.cveoy.top/t/topic/qc3v 著作权归作者所有。请勿转载和采集!