【发布时间】:2012-04-30 15:15:33
【问题描述】:
我正在尝试(使用一个小 Python 脚本)将来自在线网页的 HTML 表格的内容放入 Excel 工作表中。
一切都运行良好,除了“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 表中会发生任何事情,但是当我打印 var 的内容时......我看到了我应该看到的!
一小时后我一直在尝试修复它,但我仍然不明白发生了什么。 如果你们中的一些人可以帮助我,那应该非常好。
【问题讨论】:
-
我不明白问题到底是什么。能否请您扩展“--所以 Excel 工作表中的任何内容,但是当我打印 var 的内容时......我看到了我应该看到的内容!”句子,拜托。
-
对不起!我的意思是,hum(等于 td.text)返回我想要放入 excel 表中的值(当我打印它时,我看到了我想在 excel 表中写的内容)。
-
ws.write(x,y,td.text) 实际上返回了这个错误:ValueError: column index (257) not an int in range(256)
-
我刚刚尝试了将文件编码修复为“# -- coding: utf-8 --”的脚本,并删除了 wb.save 旁边和 tableauGood 之前的那些星号:它工作正常。我不确定这是否重要,但您使用的是哪个 Python 版本?
-
2.7.1 ...当我将 wb.save 放在 ws.write 之后似乎有效。所以数据很好地写在了 excel 表中,但是现在,当脚本通过第二个国家和机构拉入 Excel 时,我收到此错误:异常:尝试覆盖单元格:sheetname=u'BULATS_IA'rowx=1 colx =0 x 增加了所以我不明白
标签: python html excel beautifulsoup html-table