[英]Python Beautiful Soup 4 Get Children of Element with .select()
[英]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>°</span> / <span class="lo">L <span>11</span>°</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>°</span> / <span class="lo">L <span>15</span>°</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.