You can use the BeautifulSoup library in Python to parse the HTML file and find the desired element. Here is an example code snippet that finds the 'Paragraph 2' element under the 'Title 1' heading:

from bs4 import BeautifulSoup

# read the HTML file
with open('filename.html') as fp:
    soup = BeautifulSoup(fp, 'html.parser')

# find the 'Title 1' heading element
title1 = soup.find('h1', text='Title 1')

# find the 'Paragraph 2' element under the 'Title 1' heading
paragraph2 = title1.find_next_sibling('p', text='Paragraph 2')

# print the text of the 'Paragraph 2' element
print(paragraph2.text)

This code first reads the HTML file using the open function and passes it to the BeautifulSoup constructor to create a parse tree. Then it finds the 'Title 1' heading element using the find method and passes the text to match as an argument. Finally, it finds the next sibling element that is a 'p' tag and has the text 'Paragraph 2' using the find_next_sibling method, and prints its text using the text property.

Find Specific Paragraph Under a Heading in HTML Using Python

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

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