2013-04-03 45 views
0

我正在嘗試查找給定網頁中的下一個ul元素。使用BeautifulSoup獲取下一個UL元素

我開始在我的迴應到美麗的湯,像這樣堵漏:

soup = BeautifulSoup(response.context) 

打印出response.context提供了以下

print(response.context) 
<!DOCTYPE html> 
<html> 
    <head> 
     <title> | FollowUp</title> 
     <meta name='viewport' content='width=device-width, initial-scale=1.0'> 
     <link href='/static/css/bootstrap.min.css' rel='stylesheet' media='screen'> 
    </head> 

    <body> 
     <div class='navbar'> 
      <div class='navbar-inner'> 
       <a class='brand' href='/'>TellMe.cat</a> 
       <ul class='nav'> 
        <li><a href='list'>My Stories</a></li> 
        <li><a href='add'>Add Story</a></li> 
        <li><a href='respond'>Add Update</a></li> 
       </ul> 

       <form class='navbar-form pull-right' action='process_logout' method='post'> 
        <input type='hidden' name='csrfmiddlewaretoken' value='RxquwEsaS5Bn1MsKOIJP8uLtRZ9yDusH' /> 
        Hello add! 
        <button class='btn btn-small'>Logout</button> 
       </form> 

      </div> 
     </div> 

     <div class='container'> 

<ul id='items'> 
<ul> 
<li><a href='http://www.example.org'>http://www.example.org</a></li> 
<ul> 
<p>There have been no follow ups.</p> 
</ul> 
</ul> 
</ul> 

     </div> 

     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
     <script src='/static/js/bootstrap.min.js'></script> 

    </body> 
</html> 

我試圖讓則名爲「上行項目。我這樣做:

items = soup.find(id='items') 

這給了我正確的UL和所有的孩子。然而調用

items.find_next('ul') 

給出

TypeError: 'NoneType' object is not callable 

錯誤儘管這似乎是它是如何設想被稱作accorind到美麗的湯文檔:https://beautiful-soup-4.readthedocs.org/en/latest/#find-all-next-and-find-next

我在做什麼錯誤?

+0

你不能'find_all'返回一個列表? – karthikr 2013-04-03 19:03:19

+0

我不能,因爲它給出了同樣的錯誤。項目是BeautifulSoup.Tag類型,不是NoneType – Atrus 2013-04-03 19:14:56

+0

'dir()'是你的朋友。 http://docs.python.org/2/library/functions.html#dir或者在ipython中運行它並使用tab完成。 – hughdbrown 2013-04-03 19:18:06

回答

2

製作一個virtualenv,pip install BeautifulSoup requests,打開python控制檯。

import BeautifulSoup 
import requests 

html = requests.get("http://yahoo.com").text 
b = BeautifulSoup.BeautifulSoup(html) 
m = b.find(id='masthead') 
item = m.findNext('ul') 

dir(m)告訴你m的功能。你可以看到你想要findNext

您還可能發現ipython是一個更容易運行python的shell。您可以輸入變量的名稱並點擊Tab查看成員變量。