Python Code to Extract Paragraphs with Heading from HTML
Here's the complete Python code that can help you find the relevant paragraph with a heading in the "index.html" file and return the heading and all the text of the paragraphs under that heading: \n\npython\nimport re\nfrom bs4 import BeautifulSoup\n\n# Open and read the HTML file\nwith open(\"index.html\", \"r\") as file:\n html_content = file.read()\n\n# Create BeautifulSoup object to parse the HTML\nsoup = BeautifulSoup(html_content, \"html.parser\")\n\n# Prompt user for the desired heading to search for\nheading_to_search = input(\"Enter the heading to search for: \")\n\n# Find the heading element with the given text\nheading_element = soup.find(\"h1\", text=heading_to_search)\n\nif heading_element:\n # Find all the paragraphs under the heading\n paragraphs = heading_element.find_next_siblings(\"p\")\n\n if paragraphs:\n # Extract the heading and text of the paragraphs\n heading = heading_element.text.strip()\n paragraph_texts = [p.get_text(strip=True) for p in paragraphs]\n\n # Print the results\n print(\"Heading:\", heading)\n print(\"Paragraphs:\")\n for paragraph in paragraph_texts:\n print(paragraph)\n else:\n print(\"No paragraphs found under the heading:\", heading_to_search)\nelse:\n print(\"Heading not found:\", heading_to_search)\n\n\nMake sure you have the beautifulsoup4 library installed. You can install it by running pip install beautifulsoup4 in your terminal.
原文地址: https://www.cveoy.top/t/topic/qc2y 著作权归作者所有。请勿转载和采集!