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
Ewig
V2EX  ›  Python

scrapy 中转换 utf-8 后说没有 xpath

  •  
  •   Ewig · 2019-01-01 17:39:51 +08:00 · 2248 次点击
    这是一个创建于 1913 天前的主题,其中的信息可能已经有所发展或是发生改变。

    response.body.decode(encoding="utf-8") linkList =response.body.decode(encoding="utf-8").xpath( '//td[@class="pming_black12 ms-rteTableOddCol-BlueTable_CHI"]/a/@href')

    报错如下

    ttributeError: 'str' object has no attribute 'xpath' 请问如何写才是正确的

    10 条回复    2019-01-02 17:39:00 +08:00
    j0hnj
        1
    j0hnj  
       2019-01-01 17:54:03 +08:00
    随手查了一下,`xpath` 是 response 对象的方法:

    https://doc.scrapy.org/en/latest/topics/request-response.html#response-subclasses
    chengxiao
        2
    chengxiao  
       2019-01-01 18:02:45 +08:00
    先 xpath 再 encoding,而且 xpath 对象需要 extract
    Ewig
        3
    Ewig  
    OP
       2019-01-01 18:21:31 +08:00
    @j0hnj 我知道啊,现在怎么写才是正确的
    Ewig
        4
    Ewig  
    OP
       2019-01-01 18:22:25 +08:00
    @chengxiao linkList =response.xpath(u'//td[@class="pming_black12 ms-rteTableOddCol-BlueTable_CHI"]/a/@href').extract()这样写就是返回空了,你在 encoding 也不对啊
    ioven
        5
    ioven  
       2019-01-01 19:43:03 +08:00
    @Ewig xpath 写错了吧,而且 href 不需要解码
    xiaoxinxiaobai
        6
    xiaoxinxiaobai  
       2019-01-01 19:57:53 +08:00 via Android   ❤️ 1
    真可怕
    15399905591
        7
    15399905591  
       2019-01-02 09:46:39 +08:00
    response.xpath( '//td[@class="pming_black12 ms-rteTableOddCol-BlueTable_CHI"]/a/@href')

    有什么问题???
    animal
        8
    animal  
       2019-01-02 11:29:09 +08:00 via Android
    楼主这个用法不太对。1.xpath 是 selector 的方法,而 response.body 的类型是 bytes ; 2.楼上所说的 response.xpath 是 TextResponse 类(scrapy 的默认 downloader 会根据 content-type 自动转换)的方法,如果你用 response.xpath 提示报错,说明这个 response 的 content-type 不是文本格式(可能是图片,应用之类的)
    Ewig
        9
    Ewig  
    OP
       2019-01-02 17:38:24 +08:00
    @15399905591 我都说了这里的 response 返回的是乱码,你这样直接 xpath 匹配的肯定是空?你没明白我的意思?
    Ewig
        10
    Ewig  
    OP
       2019-01-02 17:39:00 +08:00
    @animal 因为编码不对是 乱码,所以 xpath 匹配不到
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5373 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 07:34 · PVG 15:34 · LAX 00:34 · JFK 03:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.