Find Specific Paragraph Under Heading in HTML with Python
You can use the BeautifulSoup library in Python to parse the HTML and search for the required element. Here is an example code:
from bs4 import BeautifulSoup
html = '''
<!DOCTYPE html>
<html>
<head>
<title>Document Name</title>
</head>
<body>
<h1>Title 1</h1>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<h2>Title 2</h2>
<p>Paragraph 3</p>
</body>
</html>
'''
soup = BeautifulSoup(html, 'html.parser')
heading1 = soup.find('h1', text='Title 1')
paragraph2 = heading1.find_next_sibling('p', text='Paragraph 2')
print(paragraph2)
This code first creates a BeautifulSoup object from the HTML string. Then it uses the find method to search for the <h1> element with the text 'Title 1'. Once it finds the element, it uses the find_next_sibling method to find the next <p> element with the text 'Paragraph 2'. Finally, it prints the element.
原文地址: https://www.cveoy.top/t/topic/osl1 著作权归作者所有。请勿转载和采集!