【问题标题】:XPATH to Excel Fails due to value unpacking由于值解包,XPATH 到 Excel 失败
【发布时间】:2018-09-21 21:13:29
【问题描述】:

我正在尝试编写一个 python 脚本,该脚本将来自网站的文本并将其放入 excel 中。我可以请求数据,但是将其转换为 excel 给我带来了一些困难。

from lxml import html
import requests
import xlsxwriter
import datetime

now = datetime.datetime.today().strftime('%Y-%m-%d')

page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
tree = html.fromstring(page.content)

#This will create a list of buyers
buyers = tree.xpath('//div[@title="buyer-name"]/text()')

#This will create a list of prices
prices = tree.xpath('//span[@class="item-price"]/text()')

print( 'Buyers: ', buyers)
print( 'Prices: ', prices)

expenses = (buyers, prices)

#creating excel sheet
workbook = xlsxwriter.Workbook('sales' + str(now) + '.xlsx')
worksheet = workbook.add_worksheet()

# Start from the first cell. Rows and columns are zero indexed.
row = 0
col = 0


#write data to excel
for item, cost in (expenses):
    worksheet.write(row, col,     item)
    worksheet.write(row, col + 1, cost)
    row += 1


workbook.close()

返回:回溯(最后一次调用): 文件“wRequests.py”,第 32 行,在 对于项目,成本(费用): ValueError:要解压的值太多(预期为 2)

如何解压这些值并正确加载到excel中?

【问题讨论】:

    标签: python excel


    【解决方案1】:

    尝试以下方法,它会完成你的工作:

    from lxml import html
    import requests
    import xlsxwriter
    import datetime
    
    
    now = datetime.datetime.today().strftime('%Y-%m-%d')
    
    page = requests.get('http://econpy.pythonanywhere.com/ex/001.html')
    tree = html.fromstring(page.content)
    
    #This will create a list of buyers
    buyers = tree.xpath('//div[@title="buyer-name"]/text()')
    
    #This will create a list of prices
    prices = tree.xpath('//span[@class="item-price"]/text()')
    
    print( 'Buyers: ', buyers)
    print( 'Prices: ', prices)
    
    #creating excel sheet
    workbook = xlsxwriter.Workbook('sales' + str(now) + '.xlsx')
    worksheet = workbook.add_worksheet()
    
    # Start from the first cell. Rows and columns are zero indexed.
    row = 0
    col = 0
    
    #write data to excel
    for index, buyer in enumerate(buyers):
        worksheet.write(row, col,     buyer)
        worksheet.write(row, col + 1, prices[index])
        row += 1
    
    workbook.close()
    

    说明

    现在你的expenses 变量是一个有两个列表的touple。它的结构是

    (
        ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes'],
        ['$29.95', '$8.37', '$15.26']
    )
    

    for 循环的工作方式与您在该数据上使用它的方式不同。它的基本语法是:

    for item in collection:
        print(item)
    

    但你正在使用它:

    for item, cost in (expenses):
        print(item, cost)
    

    当你以这种方式运行循环时,你不会分别得到itemcost。您一次只能从expenses touple 中获得一个元素,而不是多个。基本上你的语法是错误的。

    所以现在如果你像这样运行它

    for single_item in (expenses):
        print(single_item)
    

    输出将是:

    ['Carson Busses', 'Earl E. Byrd', 'Patty Cakes'] # output for first iteration
    ['$29.95', '$8.37', '$15.26'] # output for second iteration
    

    你看我们没有把itemcost放在一起。起初,我们得到第一个列表,即您的 item,在第二次迭代中,我们得到第二个列表,即 cost

    检查buyersprices 变量后,我发现它们的项目数量非常好,并且一个list 与其他list 对应的项目与他自己的index 相同。所以我可以任意选择一个列表,用索引对其进行迭代,并使用该索引在其他列表中找到它的对应项。它是如此简单。喜欢:

    for index, buyer in enumerate(buyers):
        print(buyer, prices[index])
    

    然后它将输出为

    Carson Busses $29.95
    Earl E. Byrd $8.37
    Patty Cakes $15.26
    

    我也可以将for循环写成

    for index, buyer in enumerate(buyers):
        print(buyers[index], prices[index])
    

    这将给出相同的输出。请注意,python 的内置 enumerate 函数会为列表的每个项目返回 indexvalue

    如果您有任何其他数据,例如customers,您可以参考index 来查找客户。如下:

    for index, buyer in enumerate(buyers):
        print(buyer, prices[index], customers[index])
        # or you can also do this
        print(buyers[index], prices[index], customers[index])
    

    希望这会有所帮助。

    【讨论】:

    • 原谅我的天真,我知道这里有什么不同,但我不清楚您如何将这些数据转换为 Excel 上的列。如果你有第三条数据怎么办:customers = tree.xpath('//div[@title="customer-name"]/text()')。我只是想了解你是如何做得更好的。感谢您的帮助!
    • 对于项目,成本(费用):worksheet.write(row, col, item) worksheet.write(row, col + 1, cost) worksheet.write(row, col + 1, customer ) row += 1. 这对于第三行是否正确?
    • 我已经用更多解释更新了答案。请检查
    猜你喜欢
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-31
    相关资源
    最近更新 更多