如何使用BeautifulSoup查找两个标签之间的所有列表项? [英] How do you find all list items between two tags with BeautifulSoup?

查看:171
本文介绍了如何使用BeautifulSoup查找两个标签之间的所有列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我只想从以下列表中拉出Child1,Child2和Child3,它位于h3的第一个实例之后和h3的下一个标记之前

For example, I'd like to pull out only Child1, Child2, and Child3 out of the below list where it is after the first instance of h3 and before the next tag of h3

<h3>HeaderName1<h3>
<ul class="prodoplist">
 <li>Parent</li>
 <li class="lev1">Child1</li>
 <li class="lev1">Child2</li>
 <li class="lev1">Child3</li>
  </ul>
  <h3>HeaderName2<h3>
   <ul class="prodoplist">
   <li>Parent2</li>
   <li class="lev1">Child4</li>
   <li class="lev1">Child5</li>
   <li class="lev1">Child6</li>
   </ul>

推荐答案

使用findChildren,如:

using findChildren like:

for ul in soup.find_all('ul'):
    print 'ul start'
    for idx, li in enumerate(ul.findChildren('li')):
        if idx in range(3):
            print li

输出:

ul start
<li>Parent</li>
<li class="lev1">Child1</li>
<li class="lev1">Child2</li>
ul start
<li>Parent2</li>
<li class="lev1">Child4</li>
<li class="lev1">Child5</li>

但是,在大多数情况下, lxml和xpath 是一种出色的解决方案:

however, as in most cases lxml and xpath is a superior solution:

from lxml import html
doc = html.parse('input.html')
print [ul.xpath('li[1] | li[2] | li[3]') for ul in doc.xpath('//ul')]

这篇关于如何使用BeautifulSoup查找两个标签之间的所有列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆