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

? scrapy 中的 xpath 怎么使用 contains( text(),‘型号’)限制结果??一直获取不到正确结果

  •  
  •   chu8129 ·
    chu8129 · 2015-06-25 11:10:42 +08:00 · 4673 次点击
    这是一个创建于 3232 天前的主题,其中的信息可能已经有所发展或是发生改变。
    scrapy获取URL为: http://product.dangdang.com/1259526222.html

    想获取型号获取不到,想问下大家怎么获取?
    1、希望brand返回的是只包括型号的div;
    2、希望通过xpath就可以获取;

    在scrapy shell中测试是可以的,但是到了编写的时候就拿不到了。。。。


    代码:

    >#coding:cp936
    from scrapy.spider import BaseSpider
    from scrapy.selector import Selector
    class dangdang(BaseSpider):
     name='dangdang'
     allowed_domains=[]
     start_urls=['http://product.dangdang.com/1259526222.html']
     def parse(self,response):
      sel=Selector(response)
      title=sel.xpath('//div[@class="head"]/h1/text()').extract()
      brand='\\u54c1\\u724c'.decode('unicode_escape')#型号
      brand=sel.xpath(('//div[@class="mall_goods_foursort_style_frame" and contains(text(),%s)]/a/text()')%(brand)).extract()
    2 条回复    2015-11-16 16:36:52 +08:00
    binbex
        1
    binbex  
       2015-06-25 12:16:46 +08:00
    curl -o 1234.html http://product.dangdang.com/1259526222.html
    然后在chrome中打开1234.html, 审查元素->Console,然后在控制台输入
    $x('//*[contains(concat(" ", @class, " ")," pro_content ")]/textarea/text()'),你试试看这个结果是不是输出了"div class="mall_goods_foursort_style" ",那你也就明白了,你要的结果是在字符串内,也就是说
    "div class="mall_goods_foursort_style" "你以为这个是xpath表达式路径,实际上这是个字符串,那你div[@class="mall_goods_foursort_style_frame"]肯定是没有结果的,你应该把$x('//*[contains(concat(" ", @class, " ")," pro_content ")]/textarea/text()')这个输出的字符串再转换为xml格式,这个用lxml的API可以做到,然后再用你上面自己的表达式应该可以了
    chu8129
        2
    chu8129  
    OP
       2015-11-16 16:36:52 +08:00
    @binbex 非常感谢
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3895 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 10:11 · PVG 18:11 · LAX 03:11 · JFK 06:11
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.