使用BeautifulSoup解析表格数据

3

我试着使用BeautifulSoup从表格中导入数据,这个表格是一个包含金银汇率信息的链接,然后我得到了以下输出结果。请告诉我如何只获取输出结果中的第一条信息,即Rs. 50550 /-. 抱歉,这是一个初学者问题。我尝试了很多方法,但是似乎都没有帮助...提前感谢。

>>> from bs4 import BeautifulSoup
>>> from urllib2 import urlopen
>>> response = urlopen('http://goldratenepal.com')
>>> table = soup.findChildren('table')
>>> my_table = table[2]
>>> rows = my_table.findChildren(['th class','tr'])
>>> for row in rows:
    cells = row.findChildren('td')
    for cell in cells:
        value = cell.string
        print value

输出:

50550卢比 /- 50650卢比 /- 880卢比 /- 43324卢比 /- 43424卢比 /- 754卢比 /-

有关信息:此网页的html文件如下:

<table align="center" id="rockartists">
    <thead>
        <tr>
            <th class="null">Gold rate of 2013-05-22</th>
            <th class="stones">Gold Rate in Kathmandu</th>
            <th class="stones">Gold Rate in Pokhara</th>
            <th class="u2">Silver</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th class="">Per 25gm</th>
            <td class="stones">Rs. 50550 /- </td>
            <td class="stones">Rs. 50650 /- </td>
            <td class="u2">Rs. 880 /-</td>
        </tr>
        <tr>
            <th class="">Per 10 gm </th>
            <td class="stones">Rs.43324/- </td>
            <td class="stones">Rs. 43424 /- </td>
            <td class="u2">Rs.754 /- </td>
        </tr>
    </tbody>
</table>

你能提供相关的HTML吗? - aIKid
1
我已经在帖子中添加了HTML文件。谢谢! - Tirtha
1个回答

0

您可以简单地选择第一个具有td标签和class="stones"属性的元素。

from bs4 import BeautifulSoup
from urllib2 import urlopen

response = urlopen('http://goldratenepal.com')
html = response.read()
soap = BeautifulSoup(html)
result = soap.find_all('td' ,{'class': 'stones'})

print result[0].text

感谢您的回答。 - Tirtha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接