将动态项目导出到cs

2024-03-28 19:10:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一只蜘蛛,它会像这样刮地:

class exhibitors_spider(scrapy.Spider):
name = "exhibitors"

url = "some url"

def _create_item_class(self, class_name, field_list):
    field_dict = {}
    for field_name in field_list:
        field_dict[field_name] = Field()
    return type(str(class_name), (DictItem,), {'fields': field_dict})

def start_requests(self):
    yield Request(url=self.url, callback=self.parse_page, dont_filter=True)

def parse_page(self, response):
        Contact_Persons = {}
        Contact_Persons_blocks = response.selector.xpath("//h2[contains(text(),'Contact person')]/..//..//div/.//li")
        if Contact_Persons_blocks:
            for i in xrange(1, len(Contact_Persons_blocks) + 1):
                cp_name = Contact_Persons_blocks[i - 1].xpath(".//a[@itemprop='name']/bdi/text()").extract_first()
                if cp_name:
                    cp_name = capwords(cp_name.encode('utf-8'))
                else:
                    cp_name = 0
                Contact_Persons.update({"Contact_Person_Name_{}".format(i): cp_name})

                cp_title = Contact_Persons_blocks[i - 1].xpath(".//div[@itemprop='jobTitle']/text()").extract_first()
                if cp_title:
                    cp_title = capwords(cp_title.encode('utf-8'))
                else:
                    cp_title = 0
                Contact_Persons.update({"Contact_Person_Title_{}".format(i): cp_title})

                cp_link = Contact_Persons_blocks[i - 1].xpath(".//a[@class='ngn-mail-link']/@href").extract_first()
                if cp_link:
                    cp_link = self.domain + cp_link
                else:
                    cp_link = 0
                Contact_Persons.update({"Contact_Person_Link{}".format(i): cp_link})

        ExhibitorsItem = self._create_item_class('ExhibitorsItem', Contact_Persons.keys())

        for cp_key in Contact_Persons.keys():
            item[cp_key] = Contact_Persons[cp_key]
        yield item

但我不知道我会提前多少项目,而且在每一页上有不同数量的项目。当我导出到CSV时,它看起来像是一个Scrapy创建了一个文件,其中包含来自第一个项目的键。我的意思是,它写所有的值,但是如果第一个项目有一个键,那么我们在CSV中只有一个键,如果剩余的项目有更多的键,它们将按错误的顺序排列。如何让Scrapy从一个拥有最多密钥的项目创建一个CSV文件?你知道吗


Tags: 项目nameselfurlfieldiftitlelink