簡體   English   中英

格式化 Scrapy 的 CSV 結果

[英]Formatting CSV Results of Scrapy

我正在嘗試抓取網站並將結果保存並格式化為 CSV 文件。 我能夠保存文件,但是有關於輸出和格式的三個問題:

  • 所有結果都位於一個單元格中,而不是位於多行中。 是否有我在列出項目時忘記使用的命令,以便它們出現在列表中?

  • 如何刪除每個結果之前的['u... (我搜索並看到了如何為print這樣做,但沒有return

  • 有沒有辦法向某些項目結果添加文本? (例如,我可以在每個交易鏈接結果的開頭添加“http://groupon.com”嗎?)

from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

from deals.items import DealsItem

class DealsSpider(BaseSpider):
    name = "groupon.com"
    allowed_domains = ["groupon.com"]
    start_urls = [
        "http://www.groupon.com/chicago/all",
        "http://www.groupon.com/new-york/all"
    ]

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        sites = hxs.select('//div[@class="page_content clearfix"]')
        items = []
        for site in sites:
            item = DealsItem()
            item['deal1']       = site.select('//div[@class="c16_grid_8"]/a/@title').extract()
            item['deal1link']   = site.select('//div[@class="c16_grid_8"]/a/@href').extract()
            item['img1']        = site.select('//div[@class="c16_grid_8"]/a/img/@src').extract()
            item['deal2']       = site.select('//div[@class="c16_grid_8 last"]/a/@title').extract()
            item['deal2link']   = site.select('//div[@class="c16_grid_8 last"]/a/@href').extract()
            item['img2']        = site.select('//div[@class="c16_grid_8 last"]/a/img/@src').extract()
            items.append(item)
        return items

編輯:現在我更好地理解了這個問題。 你的 parse() 函數應該更像下面這樣嗎? 也就是說, yield一次一個項目,而不是返回一個列表。 我懷疑您返回的列表是格式錯誤的填充到一個單元格中的內容。

def parse(self, response):
    hxs = HtmlXPathSelector(response)
    sites = hxs.select('//div[@class="page_content clearfix"]')
    for site in sites:
        item = DealsItem()
        item['deal1']       = site.select('//div[@class="c16_grid_8"]/a/@title').extract()
        item['deal1link']   = site.select('//div[@class="c16_grid_8"]/a/@href').extract()
        item['img1']        = site.select('//div[@class="c16_grid_8"]/a/img/@src').extract()
        item['deal2']       = site.select('//div[@class="c16_grid_8 last"]/a/@title').extract()
        item['deal2link']   = site.select('//div[@class="c16_grid_8 last"]/a/@href').extract()
        item['img2']        = site.select('//div[@class="c16_grid_8 last"]/a/img/@src').extract()
        yield item

看看項目管道文檔: http : //doc.scrapy.org/topics/item-pipeline.html

u' 表示 unicode 編碼。 http://docs.python.org/howto/unicode.html

>>> s = 'foo'
>>> unicode(s)
u'foo'
>>> str(unicode(s))
'foo'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM