简体   繁体   English

Python,精美汤:如何获取所需的元素

[英]Python, Beautiful Soup: how to get the desired element

I am trying to arrive to a certain element, parsing a source code of a site. 我试图到达某个元素,解析站点的源代码。 this is a snippet from the part i'm trying to parse (here until Friday), but it is the same for all the days of the week 这是我要解析的部分的片段(此处直到星期五),但一周中的所有天都相同

<div id="intForecast">
    <h2>Forecast for Rome</h2>
    <table cellspacing="0" cellpadding="0" id="nonCA">
        <tr>
            <td onclick="showDetails('1');return false" id="day1" class="on">
                <span>Thursday</span>
                <div class="intIcon"><img src="http://icons.wunderground.com/graphics/conds/2005/sunny.gif" alt="sunny" /></div>
                <div>Clear</div>
                <div><span class="hi">H <span>22</span>&deg;</span> / <span class="lo">L <span>11</span>&deg;</span></div>
            </td>
            <td onclick="showDetails('2');return false" id="day2" class="off">
                <span>Friday</span>
                <div class="intIcon"><img src="http://icons.wunderground.com/graphics/conds/2005/partlycloudy.gif" alt="partlycloudy" /></div>
                <div>Partly Cloudy</div>
                <div><span class="hi">H <span>21</span>&deg;</span> / <span class="lo">L <span>15</span>&deg;</span></div>
            </td>
        </tr>
    </table>
</div>

....and so on for all the days ....以此类推

Actually i got my result but in a ugly way i think: 其实我得到了我的结果,但是我以一种丑陋的方式认为:

forecastFriday= soup.find('div',text='Friday').findNext('div').findNext('div').string

now, as you can see i go deep down the elements repeating .findNext('div') and finally arrive at .string 现在,如您所见,我深入研究了重复.findNext('div')的元素,最后到达了.string

I want to get the information "Partly Cloudy" of Friday 我想获取星期五的“部分多云”信息

So any more pythonic way to do this? 那么还有其他pythonic方式可以做到这一点吗? thanks! 谢谢!

Simply find all of the <td> s and iterate over them: 只需找到所有<td>并对其进行迭代:

soup = BeautifulSoup(your_html)
div = soup('div',{'id':'intForecast'})[0]
tds = div.find('table').findAll('td')

for td in tds:
    day = td('span')[0].text
    forecast = td('div')[1].text
    print day, forecast

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM