Search code examples
pythonxpathscrapymath-functions

Python xpath and math operators


I am trying to calculate the tax of a numerical value extracted with xpath, to save it in a csv file, but I do not know what I am doing wrong or if I need to add something else.

This the code:

         import math
         for ntp in response.css('div.content-1col-nobox'):
             price1 = ntp.xpath('normalize-space(//tr[2]/td[@id="right_cell"][1])').extract()[0].split(None,1)[0].replace(",",".")
             tax = price1 * 0.22
             price = price1 + tax

          writer.writerow({
             '*StartPrice': price,\

and this is the error that I get:

    tax = price1 * 0.22
    TypeError: can't multiply sequence by non-int of type 'float'

Any help will be appreciate it.


Solution

  • Lacking your data, this would be my suggestion:

    import math
    list_prices = ['11.15', '15.00', '1.1111']
    taxed_prices = []
    for price1 in list_prices:
        taxed = float(price1) * 1.22 # note that "* 1.22" saves you one step vis-a-vis "price *0.22 + price"
        taxed_prices.append(taxed)
    print(taxed_prices)