Подскажите, пытаюсь распарсить файл .fb2. Используют bs4, т.к. структура .fb2 похожа на xml. Но возникла проблема, каждая глава книги лежит в отдельном теге section, а каждая строка книги лежит в теге p. И при попытке пробежаться в цикле по всем тегам section, он воспринимает первый тег p в каждой главе и выводит мне просто название главы и её номер. Если сделать срез, то он считает, что первый элемент(или не важно какой укажешь) это первая строка(или какая по срезу будет) каждой главы и он мне отдаёт только эти строки. Подскажите, что делаю не так? Пример части книги приведён выше. Мой код:
def transormate_book():
with open('Book.fb2', encoding="utf-8") as file:
src = file.read()
soup = BeautifulSoup(src, 'lxml')
find_body_section = soup.find('body').find_all('section')
print(find_body_section)
for poisk_vsex_p in find_body_section:
find_all_p = poisk_vsex_p.find('p').text
print(find_all_p)
Ещё вариант кода:
from bs4 import BeautifulSoup as Soup
if __name__ == '__main__':
with open('book.fb2', 'r', encoding='utf-8') as xml:
soup = Soup(xml.read(), 'lxml')
names = [offer.find('p').text for offer in soup.find_all('section')]
print(names, sep='\n')
Как выглядит книга:
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
<description>
<title-info>
<genre>sf_history</genre>
<author>
<first-name>Jean</first-name>
<middle-name>M.</middle-name>
<last-name>Auel</last-name>
</author>
<book-title>The Land of Painted Caves</book-title>
<annotation>
<p>Thirty thousand years in the making and 31 years in the writing, Auel's overlong and underplotted sixth and final volume in the Earth's Children series (The Clan of the Cave Bear; etc.) finds Cro-Magnon Ayla; her mate, Jondalar; and their infant daughter, Jonayla, settling in with the clan of the Ninth Cave of the Zelandonaii. Animal whisperer and medicine woman Ayla is an acolyte in training to become a full-fledged Zelandoni (shaman) of the clan, but all is not rosy in this Ice Age setting; there are wild animals to face and earthquakes to survive, as well as a hunter named Balderan, who has targeted Ayla for death, and a potential cave-wrecker named Marona. While gazing on an elaborate cave painting (presumably, the Lascaux caverns in France), Ayla has an epiphany and invents the concept of art appreciation, and after she overdoses on a hallucinogenic root, Ayla and Jondalar come to understand how much they mean to one another, thus giving birth to another concept — monogamy. Otherwise, not much of dramatic interest happens, and Ayla, for all her superwomanish ways, remains unfortunately flat. Nevertheless, readers who enjoyed the previous volumes will relish the opportunity to re-enter pre-history one last time.</p>
</annotation>
<date></date>
<coverpage>
<image l:href="#cover.jpg"/></coverpage>
<lang>en</lang>
<src-lang>en</src-lang>
<sequence name="Earth Children" number="6"/>
</title-info>
<document-info>
<author>
<nickname>Джим</nickname>
</author>
<program-used>calibre 0.7.52, FictionBook Editor Release 2.6</program-used>
<date value="2011-08-22">31.3.2011</date>
<id>395f9a34-7e37-4544-bd51-8bda4807048a</id>
<version>1.0</version>
</document-info>
<publish-info>
<year>2011</year>
<isbn>0517580519</isbn>
</publish-info>
</description>
<body>
<section>
<title>
<p>DEDICATION</p>
</title>
<p>For RAEANN</p>
<p>First born, last cited, always loved,</p>
<p>and for FRANK,</p>
<p>who stands by her side,</p>
<p>and for AMELIA and BRET, ALECIA, and EMORY,</p>
<p>fine young adults,</p>
<p>with love</p>
</section>
<section>
<title>
<p>Acknowledgments</p>
</title>
<p>Dr. Rigaud's help has been invaluable beginning with my first research visit to France, and his assistance has continued over the years. I particularly enjoyed the visit, which he arranged, to a stone shelter in Gorge d'Enfer, which is still much the way it was in the Ice Age: a deep protected space, open in the front, with a level floor, a rock ceiling and a natural spring at the back. It was easy to see how it could be made into a comfortable place to live. And I appreciated his willingness to explain to reporters and other media people from many countries the interesting and important information about some of the prehistoric sites in and around Les Eyzies de Tayac when Book 5, <emphasis>The Shelters of Stone</emphasis>, was launched internationally from that location in France.</p>
<p>And most of all, for Ray, my husband, who is always there for me. Love and gratitude beyond measure.</p>
</section>
<section>
<title>
<p>Chapter 1</p>
</title>
<p>The band of travellers walked along the path between the clear sparkling water of Grass River and the black-streaked white limestone cliff, following the trail that paralleled the right bank. They went single file around the bend where the stone wall jutted out closer to the water's edge. Ahead a smaller path split off at an angle toward the crossing place, where the flowing water spread out and became shallower, bubbling around exposed rocks.</p>
<p>Just as Wolf reached the lion and leaped up to attack, keeping himself between Ayla and the big cat, she flung her spear as hard as she could. Her eye caught another one hurled at the same time. They landed almost simultaneously with an audible <emphasis>thunk</emphasis>, and <emphasis>thunk</emphasis>. Both the lion and the wolf crumpled in a heap. Ayla gasped when she saw them fall, swathed in blood, afraid that Wolf was hurt.</p>
</section>
<section>
<title>
<p>Chapter 2</p>
</title>
<p>Ayla saw the heavy paw of the lion moving</p>...```
p
способом указанным в документации к библиотеке.p
, 2 варианта как я это пробовал решить отобразил в вопросе. Возможно я что-то делаю не так