Python Code to Extract Paragraph Text Under a Specific Heading
Sure! Here's a complete Python code that uses the BeautifulSoup library to scrape a webpage and find a paragraph under a given heading: \n\npython\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef get_paragraph_by_heading(url, heading):\n # Send a GET request to the webpage\n response = requests.get(url)\n \n # Parse the HTML content using BeautifulSoup\n soup = BeautifulSoup(response.content, 'html.parser')\n \n # Find the heading element\n heading_element = soup.find('h2', text=heading)\n \n if heading_element:\n # Find the next paragraph element after the heading\n paragraph = heading_element.find_next_sibling('p')\n \n if paragraph:\n # Return the text of the paragraph\n return paragraph.get_text()\n else:\n return "No paragraph found under the heading."\n else:\n return "Heading not found in the article."\n\n# Example usage\narticle_url = "https://www.example.com/article"\ntarget_heading = "Introduction"\n\nparagraph_text = get_paragraph_by_heading(article_url, target_heading)\nprint(paragraph_text)\n\n\nMake sure to replace the article_url variable with the actual URL of the article you want to scrape, and the target_heading variable with the desired heading you want to find the paragraph under.\n\nNote: Remember to install the required libraries by running pip install requests and pip install beautifulsoup4 before running the code.
原文地址: https://www.cveoy.top/t/topic/qc2s 著作权归作者所有。请勿转载和采集!