V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
hillw4h
V2EX  ›  问与答

用 pyspider 抓取苹果团的主题标题乱码怎么解决?

  •  
  •   hillw4h · 2014-11-27 12:50:27 +08:00 · 3417 次点击
    这是一个创建于 3438 天前的主题,其中的信息可能已经有所发展或是发生改变。


    from pyspider.libs.base_handler import *
    import re

    class Handler(BaseHandler):
    
        '''
        this is a sample handler
        '''
        crawl_config = {
            "headers": {
                "User-Agent": "BaiDuSpider",
            }
        }
    
        @every(minutes=24 * 60, seconds=0)
        def on_start(self):
            self.crawl('http://www.appletuan.com/', callback=self.index_page)
    
        @config(age=10 * 24 * 60 * 60)
        def index_page(self, response):
            for each in response.doc('.topic_title a[href^="http://"]').items():
                self.crawl(each.attr.href, callback=self.detail_page)
    
        def detail_page(self, response):
            return {
                "url": response.url,
                "title": response.doc('.header h1').text(),
            }
    


    返回的标题是乱码,不过同样用于v2ex却没有,这个怎么解决?

    乱码

    7 条回复    2014-11-27 16:07:03 +08:00
    binux
        1
    binux  
       2014-11-27 14:57:40 +08:00   ❤️ 1
    ```
    doc = pyquery.PyQuery(response.text)
    return {
    "url": response.url,
    "title": doc('.header h1').text(),
    }
    ```

    这就是 lxml 的蛋疼之处,给它 unicode 它有的时候它不认,给它 bytes 它又处理不好
    https://github.com/binux/pyspider/pull/24
    hillw4h
        2
    hillw4h  
    OP
       2014-11-27 15:13:00 +08:00
    @binux 照你的方法修改之后正常了。谢谢。
    不过坦白说,没懂这样改为什么就可以了,哈哈。(issue也没看懂 - -!!)
    binux
        3
    binux  
       2014-11-27 15:16:58 +08:00
    @hillw4h 这是 lxml 的问题,换个手法,用正则手动解也是可以的
    hillw4h
        4
    hillw4h  
    OP
       2014-11-27 15:20:38 +08:00
    @binux 之前还以为是编码的问题。谢谢解答!
    btw:好喜欢你开发的这个pyspider,连我这种小菜也能抓到好多自己想抓的数据。哈哈。
    xunyu
        5
    xunyu  
       2014-11-27 15:24:09 +08:00
    @binux phantomjs_fetch里面怎么没带cookies啊
    binux
        6
    binux  
       2014-11-27 16:04:28 +08:00
    @xunyu 因为 phantomjs cookies 和我手动控制的不一样。没来得及写。
    xunyu
        7
    xunyu  
       2014-11-27 16:07:03 +08:00
    @binux 好的,那我自己做吧
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2958 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:20 · PVG 21:20 · LAX 06:20 · JFK 09:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.