推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
PythonAnswer
V2EX  ›  Python

PySpider 怎样爬一个已知的、不断生成的 URL 列表?

  •  
  •   PythonAnswer · Aug 31, 2016 · 4132 views
    This topic created in 3575 days ago, the information mentioned may be changed or developed.

    情形:

    现有一个固定格式的、大约 700w 条数据的 URL ,如 "http://example/item/%d" % (i)

    我不想生成一个这么大的列表。最科学的方法应该是弄成一个生成器,生成 1000 个 url , yield 出来,再生成 1000 个...直到一直把活干完。

    不知道 PySpider 怎样重写这个 url 。查看文档和源码,发现是用 BaseHandler 的 crawl 方法,读取一个 url 列表。

    我现在想实现:

    • 每次自动生成一定数量的 url 作为任务
    • 记住当前工作状态,比如运行的 taskid ,任务暂停、重启动时,自动从该位置生成新的 url (如从 23333 开始)

    不知有没有老大有经验?

    def urls(self):
        i=1
        while i<7000000:
            yield "http://example/item/%d" % (i)
            i += 1
    
    @every(minutes=24 * 60)
    def on_start(self):
        self.crawl(self.urls(), callback=self.index_page)
    
    6 replies    2018-12-29 09:55:50 +08:00
    binux
        1
    binux  
       Aug 31, 2016   ❤️ 1
    ```
    def on_start(self):
    for i in range(10000):
    self.crawl('data:,step%d' % i, callback=self.gen_url, save=i)

    @config(priority=0)
    def gen_url(self, respond):
    for i in range(respond.save * 700, (respond.save + 1) * 700):
    self.crawl("http://example/item/%d" % i, callback=self.parse_page)

    @config(priority=1)
    def parse_page(self, respond):
    pass
    ```
    PythonAnswer
        2
    PythonAnswer  
    OP
       Aug 31, 2016
    @binux 好巧妙,有这个 save 参数。多谢!!

    另请教老大一下,如果是个不断增长的 url 怎么办呢?现在 700w ,但是每天都在不断增长,我怎么追踪才好?

    提前致谢
    binux
        3
    binux  
       Aug 31, 2016   ❤️ 1
    @PythonAnswer 接着 self.crawl 提交就好了啊
    PythonAnswer
        4
    PythonAnswer  
    OP
       Aug 31, 2016
    多谢,我继续研究一下吧。认真看源码,发掘各种功能。

    非常好用的软件~
    figofuture
        5
    figofuture  
       Aug 31, 2016
    mark
    ddzzhen
        6
    ddzzhen  
       Dec 29, 2018
    mark 很好的使用方法
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5537 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 06:58 · PVG 14:58 · LAX 23:58 · JFK 02:58
    ♥ Do have faith in what you're doing.