推荐学习书目
› 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 · Jan 1, 2019 · 3691 views
    This topic created in 2865 days ago, the information mentioned may be changed or developed.

    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 replies  •  2019-01-02 17:39:00 +08:00
    j0hnj
    j0hnj
    Jan 1, 2019
    1
    随手查了一下,`xpath` 是 response 对象的方法:

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

    有什么问题???
    animal
    animal
    Jan 2, 2019 via Android
    8
    楼主这个用法不太对。1.xpath 是 selector 的方法,而 response.body 的类型是 bytes ; 2.楼上所说的 response.xpath 是 TextResponse 类(scrapy 的默认 downloader 会根据 content-type 自动转换)的方法,如果你用 response.xpath 提示报错,说明这个 response 的 content-type 不是文本格式(可能是图片,应用之类的)
    Ewig
    Ewig
    OP
    Jan 2, 2019
    9
    @15399905591 我都说了这里的 response 返回的是乱码,你这样直接 xpath 匹配的肯定是空?你没明白我的意思?
    Ewig
    Ewig
    OP
    Jan 2, 2019
    10
    @animal 因为编码不对是 乱码,所以 xpath 匹配不到
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2584 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 14:13 · PVG 22:13 · LAX 06:13 · JFK 09:13
    ♥ Do have faith in what you're doing.