我有这样一个HTML文档,我想在该部分中获取内容
<body>
<section class="post-content">
<h1>title</h1>
<div>balabala</div>
</section>
<body>当我使用以下代码时
soup.find_all("section", {"class": "post-content"})我得到了
<section class="post-content">
<h1>title</h1>
<div>balabala</div>
</section>但是我想要的是,我应该做什么?
发布于 2022-11-05 02:50:01
您可以使用.findChildren()方法和列表组合:
import bs4
soup = bs4.BeautifulSoup("""
<body>
<section class="post-content">
<h1>title</h1>
<div>part one</div>
</section>
<section class="post-content">
<h1>title2</h1>
<div>part two</div>
</section>
<body>
""", 'html.parser')
els = soup.find_all("section", {"class": "post-content"})
els = [list(el.findChildren()) for el in els]
print(els) # => [[<h1>title</h1>, <div>part one</div>], [<h1>title2</h1>, <div>part two</div>]]soup.find_all()调用返回元素列表,列表理解循环遍历每个元素,并将其拆分为其子元素列表。el.findChildren()返回一个迭代器,因此需要将它收集到一个带有list()的列表中。
https://stackoverflow.com/questions/74324705
复制相似问题