使用Python中的BeautifulSoup循环遍历XML表块

时间:2018-05-03 23:03:26

标签: python xml beautifulsoup

在使用漂亮的汤解析某些XML时,我有一个数据结构:

<h2>Fri 4 May</h2><table cellspacing="0" cellpadding="12">

            <tr>

                <td class="time ">6:00am</td>  

                <td class="other-details ">

                    <a class="prog-link" href="http://www.tvguide.co.uk/m-detail/157702075/137913159/breakfast" id="308829348" >

                        <div class="title" style="border-left:4px solid #CE3D32">

                            Breakfast

                        </div>

                        <div class="detail">

                        A round-up of national and international news, plus current affairs, arts and entertainment, and weather   

                            <div class="other">

                            (Subtitles) (Interactive) 

                            </div>

                            <br>





                                    <div class="rating">Rating:  <span class="rating-num">1.5</span></div>



                        </div>

                    </a>

                </td>

            </tr>
...
...
...
</table>

这些结构中有几个按时间顺序排列,连续几天都有电视指南数据。

我现在的代码是这样的:

for x in soup.select('h2'):

                for tr in soup.select('table tr'):

                    if not tr.script:

                        for td in tr.find_all('td'):

                            a = ''.join(re.sub(r'\s+', ' ', td.text))
                            b = a.strip()

                            #print x.text
                            #print b

                            if b[:1] in '0123456789':


                                date_list.append(b)


                            else:

                                if ' Rating' in b:

                                    c = b.split(' Rating')

                                else:

                                    c = b.split(' Rating')
                                    c.append(0.0)

                                desc = c[0]
                                desc_list.append(desc)


                                rating = ''.join(['Rating: ', str(c[1])])
                                rating_list.append(rating)

但是,这给了我<h2>标记中定义的每个日期实例的所有可能日期的每个块。我真正想要的是逻辑顺序:

  1. 按顺序浏览每个<h2>日期标记。
  2. 仅打印属于当天的<table>块。
  3. 我几乎在那里,只是无法弄清楚我需要做出的最终修正。

1 个答案:

答案 0 :(得分:1)

我认为这个问题可能就是&#34;汤。选择&#34;总是从XML的开头开始,因此在你的第二个汤中选择你正在查找tr的所有实例。

在下面的剪辑中,我用x.select替换了第二个汤。选择 - 然后只选择&#34; x&#34;节点而不是从头开始。

for x in soup.select('table'):

                for tr in x.select('tr'):