V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
hillw4h
V2EX  ›  问与答

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

  •  
  •   hillw4h · Nov 27, 2014 · 3811 views
    This topic created in 4174 days ago, the information mentioned may be changed or developed.


    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 replies    2014-11-27 16:07:03 +08:00
    binux
        1
    binux  
       Nov 27, 2014   ❤️ 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
       Nov 27, 2014
    @binux 照你的方法修改之后正常了。谢谢。
    不过坦白说,没懂这样改为什么就可以了,哈哈。(issue也没看懂 - -!!)
    binux
        3
    binux  
       Nov 27, 2014
    @hillw4h 这是 lxml 的问题,换个手法,用正则手动解也是可以的
    hillw4h
        4
    hillw4h  
    OP
       Nov 27, 2014
    @binux 之前还以为是编码的问题。谢谢解答!
    btw:好喜欢你开发的这个pyspider,连我这种小菜也能抓到好多自己想抓的数据。哈哈。
    xunyu
        5
    xunyu  
       Nov 27, 2014
    @binux phantomjs_fetch里面怎么没带cookies啊
    binux
        6
    binux  
       Nov 27, 2014
    @xunyu 因为 phantomjs cookies 和我手动控制的不一样。没来得及写。
    xunyu
        7
    xunyu  
       Nov 27, 2014
    @binux 好的,那我自己做吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2616 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 69ms · UTC 14:14 · PVG 22:14 · LAX 07:14 · JFK 10:14
    ♥ Do have faith in what you're doing.