【问题标题】:Using Beautiful Soup for parsing NELL Knowlege Base page使用 Beautiful Soup 解析 NELL 知识库页面
【发布时间】:2015-04-14 15:08:25
【问题描述】:

我正在使用 Beautiful Soup 来解析来自http://rtw.ml.cmu.edu/rtw/kbbrowser/ 的类别列表,我得到了这个页面的 html 代码:

<html>
    <head>
        <link href="../css/browser.css" rel="stylesheet" type="text/css"/>
        <script type="text/javascript">
            if (parent.location.href == self.location.href) {
                if (window.location.href.replace)
                    window.location.replace('index.php');
                else
                    // causes problems with back button, but works
                    window.location.href = 'index.php';
            }
        </script>
    </head>
    <body id="ontology">
    ...
    </body>
</html>

我正在使用非常简单的代码,但是当我尝试访问 &lt;body&gt; 元素时,我得到了 None

import urllib
from BeautifulSoup import BeautifulSoup
from bs4 import BeautifulSoup
import mechanize
from mechanize import Browser
import requests
import re
import os

link = 'http://rtw.ml.cmu.edu/rtw/kbbrowser/ontology.php'
pageFile = urllib.urlopen(link).read()
soup = BeautifulSoup(pageFile)

print soup.head.contents[0].name
print soup.html.contents[1].name

为什么在这种情况下头元素没有兄弟?
我得到:

AttributeError: 'NoneType' 对象没有属性 'next_element'

同时尝试获取head.next_Sibling

【问题讨论】:

    标签: python html parsing beautifulsoup html-parsing


    【解决方案1】:

    这是因为 文本节点 也是 contents 的一部分。

    不要操作contents 属性,而是使用CSS selectors 来定位类别列表。例如,您可以通过以下方式列出顶级类别:

    for li in soup.select("body#ontology > ul > li"):
        print li.find_all("a")[-1].text
    

    【讨论】:

    • @MaximRukhlov 是的,有多种方法可以定位BeautifulSoup 中的元素。我向您指出 CSS 选择器的原因是我很确定这将帮助您解析类别列表。
    猜你喜欢
    • 2020-12-01
    • 2012-06-29
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2015-11-08
    • 1970-01-01
    • 2011-09-27
    • 1970-01-01
    相关资源
    最近更新 更多