繁体   English   中英

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

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

我试图到达某个元素,解析站点的源代码。 这是我要解析的部分的片段(此处直到星期五),但一周中的所有天都相同

<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>

....以此类推

其实我得到了我的结果,但是我以一种丑陋的方式认为:

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

现在,如您所见,我深入研究了重复.findNext('div')的元素,最后到达了.string

我想获取星期五的“部分多云”信息

那么还有其他pythonic方式可以做到这一点吗? 谢谢!

只需找到所有<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