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

求教一个 lxml 抓取内容的简单问题

  •  
  •   fy ·
    fy0 · 2014-07-11 00:47:46 +08:00 · 3397 次点击
    这是一个创建于 3579 天前的主题,其中的信息可能已经有所发展或是发生改变。
    不浪费大家时间,直接上代码:


    from lxml import etree

    a = etree.HTML('<div class="ash1"><span class="mark">Vectors</span> \ <span class="mark">Background</span> \ 19.080 results </div>')

    现在我想要拿到那边的 "19,080" 几个字,应该怎么做?
    a.xpath('//div')[0].text 结果竟然是空的,真是不科学?
    6 条回复    2014-07-11 10:31:56 +08:00
    imn1
        1
    imn1  
       2014-07-11 00:55:08 +08:00   ❤️ 1
    a.xpath('//div/text()')[0] 试试
    ggarlic
        2
    ggarlic  
       2014-07-11 01:22:48 +08:00   ❤️ 1
    这坑我也踩过
    text是空的原因是:text不是你以为的意思(一个标签的text内容)。text在文档中的定义是
    Text before the first subelement. This is either a string or the value None, if there was no text.

    除了楼上的方法,你也可以用itertext()方法来遍历
    binux
        3
    binux  
       2014-07-11 02:18:11 +08:00   ❤️ 1
    a.xpath('//div')[0].text_content()
    fy
        4
    fy  
    OP
       2014-07-11 02:54:23 +08:00
    多谢几位 搞定了
    pc10201
        5
    pc10201  
       2014-07-11 09:38:06 +08:00
    我为啥总觉得正则提取比xpath好呢?
    dingyaguang117
        6
    dingyaguang117  
       2014-07-11 10:31:56 +08:00
    @pc10201 xpath 虽然会慢一点 不过写法简洁,而且准确性高
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1911 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:22 · PVG 00:22 · LAX 09:22 · JFK 12:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.