【python自学笔记】(五)yield+next的用法

       Python中的生成器类似于函数,除了不返回值并退出进程,生成器将暂停进程,保存下一次的状态。从代码角度来看,函数和生成器之间的最大区别是一个词:return更改为yield

       处理非常大的数据集合时,生成器变得非常有用,您不希望一次性存储在内存中。它对于处理极大甚至无限的系列也非常有用。

       下面是如何使用生成器打印偶数的示例。一次打印所有偶数将花费无限的时间,但生成器允许进程暂停,并在需要时返回创建偶数。

       要创建下一个连续的偶数,只需调用next()生成器对象,它将产生下一次迭代。之后yield被调用,一切都在生成功能的状态冻结,并返回值。当再次调用发生器时next(),它会yield从之前的停止位置向右拾取。

# Definition of the generator to produce even numbers.
def all_even():
    n = 0
    while True:
        yield n
        n += 2

my_gen = all_even()

# Generate the first 5 even numbers.
for i in range(5):
    print(next(my_gen))

# Now go and do some other processing.
do_something = 4
do_something += 3
print(do_something)

# Now go back to generating more even numbers.
for i in range(100):
    print(next(my_gen))

学自:优达学城:数据结构与算法

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您的问题是关于如何基于Python、Scrapy、Redis和Rule组件实现分布式爬虫爬取京东华为笔记本的。首先,您需要安装Scrapy和Redis,并在Scrapy的配置文件中添加Redis相关的配置: ```python # 在settings.py中添加以下配置 DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" SCHEDULER = "scrapy_redis.scheduler.Scheduler" SCHEDULER_PERSIST = True REDIS_URL = 'redis://localhost:6379' ``` 然后,您需要编写Spider和Item Pipeline,其中Spider负责解析并抓取网页,Item Pipeline负责处理抓取到的数据。下面是一个示例的Spider代码: ```python from scrapy_redis.spiders import RedisSpider from scrapy.selector import Selector from ..items import ProductItem class JdSpider(RedisSpider): name = 'jd' redis_key = 'jd:start_urls' def parse(self, response): sel = Selector(response) products = sel.xpath('//div[@class="gl-i-wrap"]') for product in products: item = ProductItem() item['name'] = product.xpath('div[@class="p-name"]/a/em/text()').extract_first() item['price'] = product.xpath('div[@class="p-price"]/strong/i/text()').extract_first() item['url'] = product.xpath('div[@class="p-name"]/a/@href').extract_first() yield item ``` 在Item Pipeline中,您可以对抓取到的数据进行清洗和存储,下面是一个示例的Item Pipeline代码: ```python import pymongo class JdPipeline(object): def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DATABASE', 'items') ) def open_spider(self, spider): self.client = pymongo.MongoClient(self.mongo_uri) self.db = self.client[self.mongo_db] def close_spider(self, spider): self.client.close() def process_item(self, item, spider): self.db['products'].insert(dict(item)) return item ``` 最后,您需要创建一个Redis队列,并向队列中添加起始URL,如下所示: ```python import redis r = redis.Redis(host='localhost', port=6379) r.lpush('jd:start_urls', 'https://search.jd.com/Search?keyword=%E5%8D%8E%E4%B8%BA%E7%AC%94%E8%AE%B0%E6%9C%AC&enc=utf-8') ``` 最终,您就可以运行分布式爬虫并抓取京东华为笔记本的数据了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值