2013-11-25 47 views
3

我试着用BeautifulSoup从表格中的黄金和白银速率链接表上的表格导入数据,我得到以下输出。请告诉我如何我是否可以在我的输出中获得第一个信息,即Rs。 50550/- 。对不起,问新手问题。我尝试了很多,但似乎没有帮助..预先感谢。使用beautifulsoup解析表中的数据

>>> 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/- Rs.43324/- 卢比。 43424/- Rs.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> 
+0

你能提供相关的html吗? – aIKid

+1

我已在帖子中添加了html文件..谢谢..! – Tirthajust4u

回答

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 
+0

感谢您的回答。 – Tirthajust4u