I'm working on scraping the website and I want to extract the data in between the 2 headers and tag it to first tag as key-value pair.
How to extract the text under headers (like h1 and h2) ?
soup = BeautifulSoup(page.content, 'html.parser')
items = soup.select("div.conWrap")
htag_count = []
item_header = soup.find_all(re.compile('^h[1-6]'))
for item in item_header:
htag_count.append({item.name:item.text})
print(htag_count)
This won't work if the
h_tags don't share a direct parent , but you could try looping through sibling tags after eachh_tag [and stop if the nexth_tag is reached].I couldn't test this properly since you didn't include any html snippet nor a link to the site you want to scrape, but when tried on a Wikipedia page,
hSections(after truncating and tabulating) looks like:You can also take a look at this solution if you're interested in nesting subsection into the parent sections.