Я пытаюсь создать вложенную таблицу содержимого на основе тегов заголовка HTML.
Мой HTML-файл:
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<h1>
My report Name
</h1>
<h1 id="2">First Chapter </h1>
<h2 id="3"> First Sub-chapter of the first chapter</h2>
<ul>
<h1 id="text1">Useless h1</h1>
<p>
some text
</p>
</ul>
<h2 id="4">Second Sub-chapter of the first chapter </h2>
<ul>
<h1 id="text2">Useless h1</h1>
<p>
some text
</p>
</ul>
<h1 id="5">Second Chapter </h1>
<h2 id="6">First Sub-chapter of the Second chapter </h2>
<ul>
<h1 id="text6">Useless h1</h1>
<p>
some text
</p>
</ul>
<h2 id="7">Second Sub-chapter of the Second chapter </h2>
<ul>
<h1 id="text6">Useless h1</h1>
<p>
some text
</p>
</ul>
</body>
</html>
Мой код Python:
import from lxml import html
from bs4 import BeautifulSoup as soup
import re
import codecs
#Access to the local URL(Html file)
f = codecs.open("C:\\x\\test.html", 'r')
page = f.read()
f.close()
#html parsing
page_soup = soup(page,"html.parser")
tree = html.fromstring(page)#extract report name
ref = page_soup.find("h1",{"id": False}).text.strip()
print("the name of the report is : " + ref + " \n")
chapters = page_soup.findAll('h1', attrs={'id': re.compile("^[0-9]*$")})
print("We have " + str(len(chapters)) + " chapter(s)")
for index, chapter in enumerate(chapters):
print(str(index+1) +"-" + str(chapter.text.strip()) + "\n")
sub_chapters = page_soup.findAll('h2', attrs={'id': re.compile("^[0-9]*$")})
print("We have " + str(len(sub_chapters)) + " sub_chapter(s)")
for index, sub_chapter in enumerate(sub_chapters):
print(str(index+1) +"-" +str(sub_chapter.text.strip()) + "\n")
С помощью этого кода я могу получить все главы и все подглавы, но это не моя цель.
Моя цель - получить приведенное ниже в качестве содержания:
1-First Chapter
1-First sub-chapter of the first chapter
2-Second sub-chapter of the first chapter
2-Second Chapter
1-First sub-chapter of the Second chapter
2-Second sub-chapter of the Second chapter
Любые рекомендации или идеи о том, как добиться желаемого формата содержания?