从html内容中提取数据

时间:2012-07-28 13:36:48

标签: python django beautifulsoup

我想下载一些html页面并提取信息,每个HTML页面都有table tag

<table class="sobi2Details" style='background-image: url(http://www.imd.ir/components/com_sobi2/images/backgrounds/grey.gif);border-style: solid; border-color: #808080' >
    <tr>
        <td><h1>Dr Jhon Doe</h1></td>
    </tr>
    <tr>
        <td></td>
    </tr>
    <tr>
        <td></td>
    </tr>
    <tr>
        <td>
          <div id="sobi2outer">
             <br/>
             <span id="sobi2Details_field_name" ><span id="sobi2Listing_field_name_label">name:</span>Jhon</span><br/>
             <span id="sobi2Details_field_family" ><span id="sobi2Listing_field_family_label">family:</span> Doe</span><br/>
             <span id="sobi2Details_field_tel1" ><span id="sobi2Listing_field_tel1_label">tel:</span> 33727464</span><br/>
          </div>
        </td>
    </tr>
</table>

我想访问姓名(Jhone),家人(Doe)和tel(33727464),我已使用beausiful soup通过ID访问这些span标记:

name=soup.find(id="sobi2Details_field_name").__str__()
family=soup.find(id="sobi2Details_field_family").__str__()
tel=soup.find(id="sobi2Details_field_tel1").__str__()

但我不知道如何将数据提取到这些标记中。我尝试使用childrencontent属性,但当我使用主题作为tag时它返回{{ 1}}:

None

但是我收到了这个错误:

name=soup.find(id="sobi2Details_field_name")
for child in name.children:
    #process content inside

当我在其上使用 str ()时,它不是'NoneType' object has no attribute 'children' !! 任何想法?

编辑:我的最终解决方案

None

2 个答案:

答案 0 :(得分:3)

我找到了几种方法。

from bs4 import BeautifulSoup
soup = BeautifulSoup(open(path_to_html_file))

name_span = soup.find(id="sobi2Details_field_name")

# First way: split text over ':'
# This only works because there's always a ':' before the target field
name = name_span.text.split(':')[1]

# Second way: iterate over the span strings
# The element you look for is always the last one
name = list(name_span.strings)[-1]

# Third way: iterate over 'next' elements
name = name_span.next.next.next # you can create a function to do that, it looks ugly :)

告诉我它是否有帮助。

答案 1 :(得分:1)

如果您熟悉xpath,请使用带有etree的lxml:

import urllib2
from lxml import etree

opener = urllib2.build_opener()
root = etree.HTML(opener.open("myUrl").read())

print root.xpath("//span[@id='sobi2Details_field_name']/text()")[0]