推荐学习书目
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 · Jul 11, 2014 · 3964 views
    This topic created in 4351 days ago, the information mentioned may be changed or developed.
    不浪费大家时间,直接上代码:


    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 replies    2014-07-11 10:31:56 +08:00
    imn1
        1
    imn1  
       Jul 11, 2014   ❤️ 1
    a.xpath('//div/text()')[0] 试试
    ggarlic
        2
    ggarlic  
       Jul 11, 2014   ❤️ 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  
       Jul 11, 2014   ❤️ 1
    a.xpath('//div')[0].text_content()
    fy
        4
    fy  
    OP
       Jul 11, 2014
    多谢几位 搞定了
    pc10201
        5
    pc10201  
       Jul 11, 2014
    我为啥总觉得正则提取比xpath好呢?
    dingyaguang117
        6
    dingyaguang117  
       Jul 11, 2014
    @pc10201 xpath 虽然会慢一点 不过写法简洁,而且准确性高
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   929 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 20:54 · PVG 04:54 · LAX 13:54 · JFK 16:54
    ♥ Do have faith in what you're doing.