Я написал код с использованием селена для загрузки файла Excel xlsx с веб-сайта, переименования его и последующего открытия с помощью openpyxl. однако попытка прочитать файл в кадре данных pandas с помощью openpyxl приводит к ошибке.
Ошибка следующая:
ValueError: Unable to read workbook: could not read stylesheet from ./ETF/test/test.xlsx.This is most probably because the workbook source files contain some invalid XML.Please see the exception for more details.
Файл можно без проблем открыть вручную.
Мой код выглядит так:
import os.path
import pandas as pd
import numpy as np
import time
import requests
from glob import glob
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
op = webdriver.ChromeOptions()
prefs = {"download.default_directory":os.path.abspath("./ETF/test")}
# Define download path
op.add_experimental_option("prefs", prefs)
# Google Chrome
PATH = r"./webdriver/chromedriver.exe"
#PATH = r"D:\Coding\Python\project1\webdriver\chromedriver.exe"
# Use Service to set the ChromeDriver path
service = Service(PATH)
driver = webdriver.Chrome(service=service, options=op)
wait = WebDriverWait(driver, 30)
# Download and rename file if it doesn't exist
driver.get('https://www.amundietf.de/de/professionell') # Be aware in recent times, server is often down
driver.maximize_window()
# Wait for the "Professioneller Anleger" button to be present and clickable
profanleger_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Professioneller Anleger']")))
profanleger_button.click()
# Wait for the "Akzeptieren und fortfahren" button to be clickable and click it
akzept_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "confirmDisclaimer")))
akzept_button.click()
# Wait for the "Akzeptieren und fortfahren" button to be clickable and click it
cookies_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "CookiesDisclaimerRibbonV1-AllOn")))
cookies_button.click()
time.sleep(2)
# Check whether file exists
if os.path.isfile('ETF/test/' + "Fondszusammensetzung_Amundi*"):
print("File exists.")
else:
driver.get('https://www.amundietf.de/de/professionell/products/equity/amundi-index-msci-emerging-markets-ucits-etf-dr-d/lu1737652583')
# Download file
Komp_ETF_herunterladen_xpath = "//span[@class='pr-3 bold-text']"
# Wait until the download button is clickable
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, Komp_ETF_herunterladen_xpath)))
dlbutton = driver.find_element(By.XPATH, Komp_ETF_herunterladen_xpath)
dlbutton.click()
time.sleep(20) # Waiting is somehow necessary, otherwise renaming is not successful
etf_path = './ETF/test/'
f = glob(os.path.join(etf_path, "Fondszusammensetzung_Amundi*"))[0]
os.rename(f, os.path.join(etf_path, 'test.xlsx'))
# Quit browser
driver.quit()
time.sleep(20)
df = pd.read_excel('./ETF/test/test.xlsx', engine='openpyxl', skiprows=18, skipfooter=4, header=1, usecols="B:H")
df.to_csv('./ETF/test/test.csv', sep=';', encoding='latin-1', decimal=',')
Я без проблем могу открыть и отредактировать файл в Excel. Я не вижу ошибок в файле. Как мне убедиться, что я могу прочитать файл как фрейм данных, отредактировать его, а затем экспортировать как файл CSV?
Я написал код с использованием селена для загрузки файла Excel xlsx с веб-сайта, переименования его и последующего открытия с помощью openpyxl. однако попытка прочитать файл в кадре данных pandas с помощью openpyxl приводит к ошибке. Ошибка следующая: [code]ValueError: Unable to read workbook: could not read stylesheet from ./ETF/test/test.xlsx.This is most probably because the workbook source files contain some invalid XML.Please see the exception for more details. [/code] Файл можно без проблем открыть вручную. Мой код выглядит так: [code]import os.path import pandas as pd import numpy as np import time import requests from glob import glob from selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
op = webdriver.ChromeOptions() prefs = {"download.default_directory":os.path.abspath("./ETF/test")} # Define download path op.add_experimental_option("prefs", prefs) # Google Chrome PATH = r"./webdriver/chromedriver.exe" #PATH = r"D:\Coding\Python\project1\webdriver\chromedriver.exe" # Use Service to set the ChromeDriver path service = Service(PATH) driver = webdriver.Chrome(service=service, options=op) wait = WebDriverWait(driver, 30)
# Download and rename file if it doesn't exist driver.get('https://www.amundietf.de/de/professionell') # Be aware in recent times, server is often down driver.maximize_window() # Wait for the "Professioneller Anleger" button to be present and clickable profanleger_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Professioneller Anleger']"))) profanleger_button.click() # Wait for the "Akzeptieren und fortfahren" button to be clickable and click it akzept_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "confirmDisclaimer"))) akzept_button.click() # Wait for the "Akzeptieren und fortfahren" button to be clickable and click it cookies_button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "CookiesDisclaimerRibbonV1-AllOn"))) cookies_button.click() time.sleep(2)
# Check whether file exists if os.path.isfile('ETF/test/' + "Fondszusammensetzung_Amundi*"): print("File exists.") else: driver.get('https://www.amundietf.de/de/professionell/products/equity/amundi-index-msci-emerging-markets-ucits-etf-dr-d/lu1737652583') # Download file Komp_ETF_herunterladen_xpath = "//span[@class='pr-3 bold-text']" # Wait until the download button is clickable WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, Komp_ETF_herunterladen_xpath))) dlbutton = driver.find_element(By.XPATH, Komp_ETF_herunterladen_xpath) dlbutton.click() time.sleep(20) # Waiting is somehow necessary, otherwise renaming is not successful etf_path = './ETF/test/' f = glob(os.path.join(etf_path, "Fondszusammensetzung_Amundi*"))[0] os.rename(f, os.path.join(etf_path, 'test.xlsx'))
# Quit browser driver.quit() time.sleep(20)
df = pd.read_excel('./ETF/test/test.xlsx', engine='openpyxl', skiprows=18, skipfooter=4, header=1, usecols="B:H") df.to_csv('./ETF/test/test.csv', sep=';', encoding='latin-1', decimal=',') [/code] Я без проблем могу открыть и отредактировать файл в Excel. Я не вижу ошибок в файле. Как мне убедиться, что я могу прочитать файл как фрейм данных, отредактировать его, а затем экспортировать как файл CSV?
Предположим, у меня есть кадр данных размером 2*3:
df = pd.DataFrame({'A': , 'B': , 'C': }) А Б С 0 1 3 5 1 2 4 6 Мне интересно, как преобразовать df в кадр данных (2*3)*1, который имеет следующую форму? Я пробовал pd.DataFrame.explode() и...
erryone. Вот с этой проблемой я столкнулся. Разделение нескольких страниц листов в формате xlsx на несколько файлов xlsx, содержащих только одну страницу листа, с использованием POI-OOXML 4.1.2 приводит к несовместимым стилям при копировании. Как...
У меня есть несколько листов .xlyx, которые я хочу считать в новый файл .xlyx и добавить их на отдельные вкладки. Прямо сейчас я вручную создал вкладки для каждого.
Мне было интересно, как я могу использовать Openxyl для чтения каждого из этих...
Я создал большой двоичный объект Azure с помощью файла Excel (.xlsx). Я хочу прочитать то же самое, используя Java (Apache-poi) и Azure SDK, не загружая его локально. Я могу загрузить большой двоичный объект/файл во временное расположение и...
Я создал большой двоичный объект Azure с помощью файла Excel (.xlsx). Я хочу прочитать то же самое, используя Java (Apache-poi) и Azure SDK, не загружая его локально. Я могу загрузить большой двоичный объект/файл во временное расположение и...