2012-04-19 14 views
1

我想(用一個小小的python腳本)將HTML表格的內容從在線網頁放入Excel工作表中。BeautifulSoup + xlwt:在Excel中放入一個HTML表格的內容

除了「Excel事物」之外,所有的工作都很好。

#!/usr/bin/python 
# --*-- coding:UTF-8 --*-- 

import xlwt 
from urllib2 import urlopen 
import sys 
import re 
from bs4 import BeautifulSoup as soup 
import urllib 

def BULATS_IA(name_excel): 
    """ Function for fetching the BULATS AGENTS GLOBAL LIST""" 

ws = wb.add_sheet("BULATS_IA") # I add a sheet in my excel file 

    Countries_List = ['United Kingdom','Albania','Andorra'] 
    Longueur = len(Countries_List) 
    number = 1 


    print("Starting to fetch ...") 

    for Countries in Countries_List: 
     x = 0 
     y = 0 

     print("Fectching country %s on %s" % (number, Longueur)) 
     number = number + 1 
     htmlSource = urllib.urlopen("http://www.cambridgeesol.org/institutions/results.php?region=%s&type=&BULATS=on" % (Countries)).read() 
     s = soup(htmlSource) 
     **tableauGood = s.findAll('table') 
     try: 
      rows = tableauGood[3].findAll('tr') 
      for tr in rows: 
       cols = tr.findAll('td') 
       y = 0 
       x = x + 1 
       for td in cols: 
        hum = td.text 

        ws.write(x,y,td.text) 
        y = y + 1 
        wb.save("%s.xls" % name_excel)** 

     except (IndexError): 
      pass 

    print("Finished for IA") 



name_doc_out = raw_input("What do you want for name for the Excel output document ? >>> ") 
wb = xlwt.Workbook(encoding='utf-8') 
print("Starting with BULATS Agents, then with BULATS IA") 
#BULATS_AGENTS(name_doc_out) 
BULATS_IA(name_doc_out) 

- 那麼什麼是要在Excel工作表,但是當我打印變種的內容......我明白我應該看看!

我試圖解決它,因爲一小時,但我仍然不明白會發生什麼事。 如果你們中有些人可以幫我一把,那應該非常好。

+0

我無法理解的問題,實際上是什麼。你能否詳細說一下「 - 因此,Excel表格中的任何內容都會發生變化,但是當我打印var的內容時......我看到了我應該看到的內容!」句子。 – Nemoverflow 2012-04-19 06:11:39

+1

對不起!我的意思是哼聲(相當於td.text)將我想要放入Excel表格中的值(當我打印它時,我看到我想要寫入Excel表格中)。 – 2012-04-19 06:25:28

+0

ws.write(x,y,td.text)實際上是返回給我這個錯誤:ValueError:列索引(257)不是int在範圍內(256) – 2012-04-19 06:26:22

回答

0

我已嘗試您的應用程序。我很確定td.text的輸出與excel文件相同。那麼你的問題是什麼?如果內容不是你想要的,你應該檢查BeautifulSoap的使用情況。 更進一步,你可能需要做以下幾點:

  for td in cols: 
       hum = td.text.replace(" ", " ") 
       print hum 
       ws.write(x,y,hum) 
+0

感謝您的幫助傢伙!它似乎現在工作...我不知道發生了什麼...但我總是在第一個國家後出現此錯誤: 例外:嘗試覆蓋單元格:sheetname = u'BULATS_IA'rowx = 1 colx = 0 – 2012-04-19 06:45:56

相關問題