簡體   English   中英

如何解決“ ValueError:無法轉換為Excel”? (使用Python和openpyxl)

[英]How to solve “ValueError: Cannot convert to Excel”? (Using Python & openpyxl)

我正在使用lxml從網站上抓取價格,我想使用openpyxl將價格插入到現有的excel文件中。 運行代碼時,出現錯誤“ ValueError:無法將['$ 364']轉換為Excel”('$ 364是報廢價格)。 我該如何解決? 問題似乎出現在代碼的第11行: sheet['A1'] = price 我的上等代碼如下。

from lxml import html
import requests
page = requests.get('http://www.randomlengths.com/Woodwire/RL-Lbr-Pnl/')
tree = html.fromstring(page.content)
price = tree.xpath('//*[@id="main-frame"]/div/div[1]/table/tbody/tr[2]/td[2]/strong/text()')
print(price)

import openpyxl
xfile = openpyxl.load_workbook('C:/Users/noah.merkousko/randomlengthslumber.xlsx')
sheet = xfile.get_sheet_by_name('Framing Lumber')
sheet['A1'] = price
xfile.save('random lengths lumber test.xls') 

“ ValueError:無法將['$ 364']轉換為Excel”告訴您該錯誤。 您試圖將列表['$364']放入包含值的單元格中。 您可以通過將其放入Excel時建立索引或從在線解析時建立索引來解決此問題。

選項1:

price = tree.xpath('//*[@id="main-frame"]/div/div[1]/table/tbody/tr[2]/td[2]/strong/text()')[0] # index at 0

選項2:

sheet['A1'] = price[0] # index when you put into Excel

值得注意的是,如果更改了站點並且該值不再位於'//*[@id="main-frame"]/div/div[1]/table/tbody/tr[2]/td[2]/strong/text()' ,則可能會引入IndexValue錯誤。 '//*[@id="main-frame"]/div/div[1]/table/tbody/tr[2]/td[2]/strong/text()' ,但可以解決您的問題

您可以捕獲該錯誤作為例外。

try:
    sheet['A1'] = price
except ValueError:
    print("Handling the error case")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM