达到特定分区时的触发事件

时间:2016-04-28 19:24:20

标签: python parsing beautifulsoup

所以我想打印与该号码相关的信息旁边的数字。问题是,有时候有4个项目,有时候有5个项目,这意味着我需要某种计数器。当我到达特定div时,我试图触发一个事件来打印新号码。这是代码:

<div class="result">
  <span class="number"><a href="####">####
  <span class="d" id="number">
  </span>
  </span></a> 
<div class="rm">
  <span class="detail"><span class="cloud" title="system"></span> information</span>
  <span class="detail"><span class="marker" title="location"></span> information</span>
  <br/>
  <span class="detail"><span class="cog" title="public"></span> information</span>
  <br/>
  <span class="detail"><span class="lock" title="name"></span> information</span>
  <br/>
</div>
  <span class="default">word</span>
</div>
<div class="result">
  <span class="number"><a href="####">####
  <span class="d" id="number">
  </span>
  </span></a> 
<div class="rm">
  <span class="detail"><span class="cloud" title="system"></span> information</span>
  <span class="detail"><span class="marker" title="location"></span> information</span>
  <br/>
  <span class="detail"><span class="cog" title="public"></span> information</span>
  <br/>
  <span class="detail"><span class="lock" title="name"></span> information</span>
  <br/>
</div>
  <span class="default">word</span>
</div>

基本上,我想将span类号中的数字与每个细节范围内的所有信息相关联。我把它放到excel表中;数字在A列和B栏中的信息。有没有办法用BeautifulSoup说,&#34;当你到达&#39; div class = result&#39;时,把数字放在A栏的新行上并将与其相关的信息放在B栏旁边的列表中。我会发布代码,但我根本不知道该怎么做,我正在寻找一些方向。谢谢!

2 个答案:

答案 0 :(得分:0)

我认为最简单的方法是:

# grab all the result elements
divs = soup.findAll('div', attrs={"class":"result"})
# loop through the result elements
for div in divs:
    number = div.find('span', {'class': 'number'})
    # do the rest of your code here

答案 1 :(得分:-1)

如果您要显示您想要的结果的确切结果或格式,将会很容易。否则@wes提到的就足够了。谢谢!