【问题标题】:XML to XLSX in PythonPython 中的 XML 到 XLSX
【发布时间】:2017-06-30 03:08:23
【问题描述】:

我已经到处寻找答案,但似乎没有明确的解决方案。这里是:

from selenium import webdriver

chromedriver_path = ("localchromedrive/chromedriver.exe")
chromeOptions = webdriver.ChromeOptions()
MSCI_dir = ("mylocaldrive")
prefs = {"download.default_directory" : MSCI_dir}
chromeOptions.add_experimental_option("prefs", prefs)
driver = webdriver.Chrome(chromedriver_path,chrome_options=chromeOptions)
url = "https://www.ishares.com/us/239637/fund-download.dl"
driver.get(url)

文件现在下载到本地路径并保存如下:

temp_path = "mylocaldrive\iShares-MSCI-Emerging-Markets-ETF_fund.xls"

此文件保存为“.xls”文件类型,但它显然是 XML 文件。有关在记事本中打开的文件,请参见下文。

我试过 xlrd:

import xlrd
book = xlrd.open_workbook(temp_path)
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\xef\xbb\xbf<?xml'

我试过 xml.etree:

import xml.etree.ElementTree as ET
tree = ET.parse(temp_path)
File "<string>", line unknown
ParseError: mismatched tag: line 16, column 2`

我试过 xlwings:

wb = xw.Book(temp_path)
wb.save(xlsx_path)
wb.close()`

它看起来很有效,但是当我尝试使用 pandas 时,我得到了这个:

pd.read_excel(xlsx_path)
XLRDError: Unsupported format, or corrupt file: Expected BOF record; found b'\xef\xbb\xbf<?xml'`

我试过 BeautifulSoup

from bs4 import BeautifulSoup`
soup = BeautifulSoup(open(temp_path), "xml")`

In [1]: soup
Out[1]: <?xml version="1.0" encoding="utf-8"?>`

In [2]: soup.contents
Out[2]: []`

In [3]: soup.get_text()
Out[3]: ''`

我正在寻找使用 pandas 访问此文件的明确方法。让我知道您需要我提供哪些我缺少的信息。

【问题讨论】:

标签: xml xls


【解决方案1】:

我认为您的问题是该文件不是 XLS,而是 XLSX 文件,它是 Microsoft 为减少 DOC 和 XLS 文件大小而制作的特殊 XML 文件。

看: https://en.wikipedia.org/wiki/Microsoft_Office_XML_formats

https://msdn.microsoft.com/en-us/library/dd922181(v=office.12).aspx

【讨论】:

    猜你喜欢
    • 2011-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-02
    • 2021-12-04
    • 1970-01-01
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多