V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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
pc10201
V2EX  ›  Python

scrapy 如何采集分页数据?

  •  
  •   pc10201 · 2014-09-24 10:48:35 +08:00 · 10575 次点击
    这是一个创建于 3524 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如这个网页
    http://www.cs.com.cn/xwzx/hg/201409/t20140924_4521344.html

    正文分成了好几个分页来显示,骗PV可耻啊

    我想用scrapy把这个正文合并起来,看文档中没找到合并的办法

    就想到一个思路,如果发现有分页,将网页内容合并起来,再用lxml和xpath提取
    测试了一下,思路是可行的,我就想问一下,scrapy是否有自带的方法能更优雅的实现这一过程?

    核心代码 片断
    from lxml import html
    import HTMLParser
    import requests
    import re

    def innerHTML(node):
    buildString = ''
    for child in node:
    buildString += html.tostring(child)
    return HTMLParser.HTMLParser().unescape(buildString)

    encoding = 'gbk'

    source=response.body.decode(encoding,'ignore')

    p=re.search(r'countPage = (.*?)/',response.body)
    if p:
    for i in xrange(1,int(p.group(1))):
    url='%s_%d.html' %(response.url.replace('.html',''),i)
    source =source+ requests.get(url,headers=headers).content.decode(encoding,'ignore')
    content=html.fromstring(source).xpath('//div[@class="Dtext z_content"]')
    content=innerHTML(content)
    第 1 条附言  ·  2014-09-24 11:43:10 +08:00
    这样做的好处可以将内容合并放到一个item中
    如果要放到不同的item,可以用yield request来做~
    7 条回复    2014-09-26 14:08:11 +08:00
    aisensiy
        1
    aisensiy  
       2014-09-24 11:08:20 +08:00
    我想是不可以的,需要你自己去实现
    binux
        2
    binux  
       2014-09-24 11:09:43 +08:00
    这段代码和 scrapy 有什么关系。。
    pc10201
        3
    pc10201  
    OP
       2014-09-24 11:30:26 +08:00
    @binux 我用scrapy获取到第一个网页的response,分页数据用requests来获取~
    Melodic
        4
    Melodic  
       2014-09-24 13:26:04 +08:00
    scrapy不需要合并,只需要在第一页抓完之后,返回Request,参数中携带下一页的url和自己的分析函数的回调即可

    def parse(self, response):
    .
    .
    .
    url = 下一页的url
    yield scrapy.Request(url, callback=self.parse)

    至于下一页的url是你for循环出来还是自己拼接的,就要具体分析了。
    forever139
        5
    forever139  
       2014-09-24 13:54:31 +08:00
    楼主的意思我懂,你这种做法其实也是可以的,官方是推荐都能通过自己的requests管理,如果有额外的参数,你可以通过request的meta属性来yield给下个request,然后在response中取出来,这样你就可以是一个item.不过你这种情况可能传递的内容比较多,效率比较低。
    pc10201
        6
    pc10201  
    OP
       2014-09-26 10:20:27 +08:00
    @forever139 亲,能否给一段示例代码或相关网页?我就是不知道怎么将response.body合并~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1010 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 22:59 · PVG 06:59 · LAX 15:59 · JFK 18:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.