Reputation: 17
I am trying to isolate the integer from some HTML, e.g. "
5,500 miles
".
import scrapy
class AlfaShortSpider(scrapy.Spider):
name = 'alfashort'
def start_requests(self):
yield scrapy.Request(url = 'https://www.pistonheads.com/classifieds/used-cars/alfa-romeo/giulia',
callback = self.parse_data)
def parse_data( self, response ):
advert = response.xpath( '//*[@class="ad-listing"]')
title = advert.xpath( './/*[@class="listing-headline"]//h3/text()' ).extract()
price = advert.xpath( './/*[@class="price"]/text()' ).extract()
mileage = advert.xpath( './/*[@class="specs"]//li[1]/text()' ).extract()
mileage = [item.strip() for item in mileage]
mileage = [item.replace(',','') for item in mileage]
mileage = [item.replace(' miles','') for item in mileage]
for item in zip(title,price,mileage):
price_data = {
'title' : item[0],
'price' : item[1],
'mileage' : item[2]
}
yield price_data
My code successfully removes the comma and "miles" but in my CSV output I get unwanted blank rows in this column which I presume are due to the carriage returns in the original source. My CSV looks like this:
So the title and price columns are fine. But the Mileage column is where the error is.
is there something wrong with my Strip command?
Upvotes: 0
Views: 54
Reputation: 71
Just change the XPath for mileage
from
mileage = advert.xpath( './/*[@class="specs"]//li[1]/text()' ).extract()
to
mileage = advert.xpath( './/*[@class="specs"]//li[1]/text()[2]' ).extract()
You will get output correct output:
title,price,mileage
ALFA ROMEO GIULIA (0) V6 BITURBO QUADRIFOGLIO 2018 (2018),"£48,500",5500
ULEZ CHARGE EXEMPT! EURO 6 (2017),"£25,695",11450
ALFA ROMEO GIULIA (0) V6 BITURBO QUADRIFOGLIO NRING 2019 (2019),"£83,500",100
ALFA ROMEO GIULIA (0) TD SPECIALE 2017 (2017),"£22,500",23700
Upvotes: 1