我已经用python scrapy编写了一个脚本来解析价格比较网站上的一些项目。我对结果不满意,因为脚本会将所有结果排成一行,如:
price,seller
"4,4,4,4,4,4,4,4,4,4","Opinie o ewitaldo.pl,Opinie o dobrazielarnia.pl,Opinie o brokulek.pl,Opinie o delikatesyznatury.pl,Opinie o bialastokrotka.pl,Opinie o aleeko.pl,Opinie o aptekamini.pl,Opinie o farmeko24.pl,Opinie o straganzdrowia.pl,Opinie o bdsklep.pl"
我需要的是:
price,seller
4,Opinie o ewitaldo.pl
4,Opinie o dobrazielarnia.pl
4,Opinie o brokulek.pl
4,Opinie o delikatesyznatury.pl
4,Opinie o bialastokrotka.pl
4,Opinie o aleeko.pl
4,Opinie o aptekamini.pl
4,Opinie o farmeko24.pl
4,Opinie o straganzdrowia.pl
4,Opinie o bdsklep.pl
这是我的蜘蛛代码:
import scrapy
from ceneo.items import CeneoItem
class QuotesSpider(scrapy.Spider):
name = "quotes"
def start_requests(self):
urls = [
'https://www.ceneo.pl/33022301'
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
items = CeneoItem()
sale_price = response.xpath('(//td[@class="cell-price"] /a/span/span/span[@class="value"]/text())[position() <= 10]').extract()
seller = response.xpath('(//tr/td/div/ul/li/a[@class="js_product-offer-link"]/text())[position()<=10]').extract()
items['product_sale_price'] = ''.join(sale_price).strip()
items['product_seller'] = ''.join(seller).strip()
yield {'price': sale_price, 'seller': seller}
应该更改什么才能获得更好的csv输出?
答案 0 :(得分:3)
您必须使用zip()
将price
与seller
分组,然后分别yield
分组
def parse(self, response):
all_prices = response.xpath('(//td[@class="cell-price"] /a/span/span/span[@class="value"]/text())[position() <= 10]').extract()
all_sellers = response.xpath('(//tr/td/div/ul/li/a[@class="js_product-offer-link"]/text())[position()<=10]').extract()
for price, seller in zip(all_prices, all_sellers):
yield {'price': price.strip(), 'seller': seller.strip()}
答案 1 :(得分:-1)
您拥有sale_price和卖家价值。
sale_data = [sale_price, seller]
final_list = [zip(*sale_data)[i] for i in xrange(len(sale_price))]
这个final_list会有不同的结果。
[(u'2893', u'Opinie o klimasklep.pl'), (u'2999', u'Opinie o wentsystem.com'), (u'3419', u'Opinie o master.sklep.pl'), (u'2893', u'Opinie o elektrozilla.pl'), (u'2895', u'Opinie o mk.net.pl'), (u'2949', u'Opinie o e-master.pl'), (u'2960', u'Opinie o kajt24.pl'), (u'2999', u'Opinie o klimatop.pl'), (u'2999', u'Opinie o fabryka-komfortu.pl'), (u'3041', u'Opinie o pajm.pl')]