正确安排两个for循环的结果

Arranging properly the results of two for loops

正如您将从下面的代码中看到的,我正在使用 Scrapy 抓取一些信息。一切正常,我只是对抓取数据的存储方式不满意。使用当前代码,我得到的结果是 'X' 的一列和 'Y' 的一列并排(这很好),但是 'U' 的结果显示为一行它是来自第二个循环的 运行。所以我想要的是将抓取的数据并排在三列中:X / Y / U。有人可以帮忙吗?提前致谢!

def parse(self, response):
    U = []
    for l in response.css('div.property-info-wrapper'):
        yield {
            'X': l.css('span.info-price::text').extract_first(),
            'Y': l.css('li::text').extract_first(),
        }

    for i in response.selector.xpath('//div[@class="property-info-location ellipsis-element-control"]/text()').extract():
        U.append(i)
    yield {'U':U}

您可以使用 itertools.zip_longest 将两个结果压缩在一起,并根据它们的真值 *.

生成它们
from itertools import zip_longest

def parse(self, response):
    locations = response.selector.xpath('//div[@class="property-info-location ellipsis-element-control"]/text()').extract()
    css = response.css('div.property-info-wrapper')

    for loc, c in zip_longest(css, locations):
        if loc:
            yield {
                'X': loc.css('span.info-price::text').extract_first(),
                'Y': loc.css('li::text').extract_first(),
            }
        if c:
            yield {'U': c}  # since spider needs to return dict

* itertools.zip_longest(*iterables, fillvalue=None): 创建一个迭代器,聚合来自每个可迭代对象的元素。如果可迭代对象的长度不均匀,则缺失值将用 fillvalue 填充。迭代一直持续到最长的迭代耗尽。