将 xlwings 与 excel 结合使用,这两种方法中哪一种是最快/首选的?

Using xlwings with excel, which of these two approaches is the quickest/ preferred?

我刚刚开始学习 Python 并且正在使用 xlwings 写入 excel 电子表格。我对编码真的很陌生(这是我的第一个问题),所以这可能是一个简单的问题,但如果有任何评论,我将不胜感激。

我正在阅读一个网站的页面源代码(使用selenium和美汤)来获取一些关于产品的信息,比如价格和重量。然后我将这些值写入 excel.

中的单元格

我有两种方法可以做到这一点 - 首先运行一个函数,然后在继续下一个函数之前将值写入 excel:

(这些是主脚本的摘录 - 两种方式都可以)

   while rowNum < lastRow + 1:    

    urlCellRef = (rowNum, colNum)
    url = wb.sheets[0].range(urlCellRef).value

    # Parse HTML with beautiful soup
    getPageSource()            

    # Find a product price field value within HTML
    getProductPrice() 
    itemPriceRef = (rowNum, colNum + 1)
    # Write price value back to Excel sheet
    wb.sheets[0].range(itemPriceRef).value = productPrice

    getProductWeight()
    itemWeightRef = (rowNum, colNum + 2)
    wb.sheets[0].range(itemWeightRef).value = productWeight     

    getProductQuantity()
    itemQuantityRef = (rowNum, colNum + 4)
    wb.sheets[0].range(itemQuantityRef).value = productQuantity

    getProductCode()
    prodCodeRef = (rowNum, colNum + 6)
    wb.sheets[0].range(prodCodeRef).value = productCode


    rowNum = rowNum + 1

第二个运行所有函数,然后一次性将每个存储值写入 excel:

   while rowNum < lastRow + 1:    

    urlCellRef = (rowNum, colNum)
    url = wb.sheets[0].range(urlCellRef).value


    getPageSource()            
    getProductPrice() 
    getProductWeight()
    getProductQuantity()
    getProductCode()


    itemPriceRef = (rowNum, colNum + 1)
    wb.sheets[0].range(itemPriceRef).value = productPrice  

    itemWeightRef = (rowNum, colNum + 2)
    wb.sheets[0].range(itemWeightRef).value = productWeight

    itemQuantityRef = (rowNum, colNum + 4)
    wb.sheets[0].range(itemQuantityRef).value = productQuantity

    prodCodeRef = (rowNum, colNum + 6)
    wb.sheets[0].range(prodCodeRef).value = productCode


    rowNum = rowNum + 1 

我想知道,执行此操作的首选方法是什么?我没有注意到太多速度差异,但我的笔记本电脑速度很慢,所以如果一种方法被认为是最佳实践,那么我宁愿采用它,因为我将增加将使用的 url 数量。

非常感谢您的帮助!

Excel 调用的开销至高无上。使用 XLWings 时,请尽可能少地写信给您的传播sheet。

我发现使用 Range 对象重写整个 sheet(或要更改的 sheet 区域)比写入单个单元格、行或列快得多.如果我不做任何繁重的数据操作,我只使用嵌套列表 - 将子列表视为列或行(为此使用转换选项)是否更好取决于你如何处理你的数据。如果您正在处理更大的数据集或进行更密集的工作,您可能需要使用 NumPy 数组或 Panda。