2016-04-14 121 views
0

我一直在尝试一段时间来从BS4的这块html中获得“$ 6.4K”,但是由于它的位置对我来说有点棘手,所以一直很困难。Python - BeautifulSoup - 抓取数据,包括Divs&Span's

<div class="blk game"> 
<div class="blk away-team"> 
<div class="pitcher players"> 
<a href="http://rosl.tu" class="player-popup" data-url="http://rosl.tu">Jake Peavy</a> 
<span class="meta stats"> 
<span class="stats"> R </span> 
$6.4K <span class="fpts" title="Projected Points" data-role="authorize" data-product="56">7.17</span> 
</span> 
</div>... 
+1

你能张贴你如何试图得到 “$ 6.4K”? – Phillip

回答

2

有很多方法。我认为最好的方法是挑选最脆弱的东西 - 如果HTML发生变化,那么这些东西不会中断。这就是说,我不知道你可以期待HTML如何一致。

所以,一种方法是选择具有“meta”标签的<span>的第三个子节点。要做到这一点,你可以这样做:

from bs4 import BeautifulSoup 
html = ''' 
<div class="blk game"> 
<div class="blk away-team"> 
<div class="pitcher players"> 
<a href="http://rosl.tu" class="player-popup" data-url="http://rosl.tu">Jake Peavy</a> 
<span class="meta stats"> 
<span class="stats"> R </span> 
$6.4K <span class="fpts" title="Projected Points" data-role="authorize" data-product="56">7.17</span> 
</span> 
</div> 
''' 

soup = BeautifulSoup(html) 
print(list(soup.find_all("span", class_="meta")[0].children)[2]) 

它打印:

$6.4K