Skip to content

Instantly share code, notes, and snippets.

@GuyMicciche
Last active August 17, 2023 20:55
Show Gist options
  • Save GuyMicciche/c67953ac9cffc2347cf8dbe96d64cba2 to your computer and use it in GitHub Desktop.
Save GuyMicciche/c67953ac9cffc2347cf8dbe96d64cba2 to your computer and use it in GitHub Desktop.
Extract the content of the second h2 tag from the list of all h2 contents
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def __init__(self):
super().__init__()
self.recording = False
self.current_data = []
self.all_h2_contents = []
def handle_starttag(self, tag, attrs):
if tag == 'h2':
self.recording = True
self.current_data = [] # Clear current data for new h2 tag
def handle_endtag(self, tag):
if self.recording and tag == 'h2':
self.recording = False
self.all_h2_contents.append(''.join(self.current_data).strip())
def handle_data(self, data):
if self.recording:
self.current_data.append(data)
parser = MyHTMLParser()
parser.feed(inputData['htmlContent'])
# Extract the content of the second h2 tag from the list of all h2 contents
extractedText = parser.all_h2_contents[1] if len(parser.all_h2_contents) > 1 else 'Not Found'
return {'extractedText': extractedText}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment