循环通过ol标签的孩子与美丽的小屋

发布于 2025-02-07 05:52:56 字数 332 浏览 1 评论 0原文

我有以下HTML结构:

<ol>
  <li>...</li>
  <div>...</div>
  <li>...</li>
</ol>

当我执行以下操作时:

for e in doc.find('ol').children:
    print(e.text)

我得到两个 li 元素,但 div

我该怎么做才能以正确的顺序获得所有这些?

I have the following html structure:

<ol>
  <li>...</li>
  <div>...</div>
  <li>...</li>
</ol>

When I do the following:

for e in doc.find('ol').children:
    print(e.text)

I get the two li elements but not the div

What can I do to get all of them in the correct order?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦情居士 2025-02-14 05:52:56

您的脚本IST工作,您可以对其进行一些调整,然后打印标签的文本:

for e in soup.find('ol').children:
    if e.name:
        print(e.text)
示例
from bs4 import BeautifulSoup

html='''
<ol>
  <li>...li1</li>
  <div>...div</div>
  <li>...li2</li>
</ol>
'''

soup = BeautifulSoup(html, 'html.parser')

for e in soup.find('ol').children:
    if e.name:
        print(e.text)
输出
...li1
...div
...li2

Your script ist working, you could adjust it a bit and just print the text of the tags:

for e in soup.find('ol').children:
    if e.name:
        print(e.text)
Example
from bs4 import BeautifulSoup

html='''
<ol>
  <li>...li1</li>
  <div>...div</div>
  <li>...li2</li>
</ol>
'''

soup = BeautifulSoup(html, 'html.parser')

for e in soup.find('ol').children:
    if e.name:
        print(e.text)
Output
...li1
...div
...li2
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文