初识python yield


for sel in response.xpath('//ul/li'):
    item = DmozItem()
    item['title'] = sel.xpath('a/text()').extract()
    item['link'] = sel.xpath('a/@href').extract()
    item['desc'] = sel.xpath('text()').extract()
    yield item


等价于:

items []
for sel in response.xpath('//ul/li'):
    item = DmozItem()
    item['title'] = sel.xpath('a/text()').extract()
    item['link'] = sel.xpath('a/@href').extract()
    item['desc'] = sel.xpath('text()').extract()
   items.append(item)
    return items

就这么简单!
posted @ 2016-03-20 13:05  高手教程  阅读(273)  评论(0编辑  收藏  举报