2013-04-03 40 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查看成员变量。