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

再请教 lxml 分析 html 的问题,涉及 xpath 语法

  •  
  •   wencan · 2017-08-11 11:48:25 +08:00 · 2034 次点击
    这是一个创建于 2443 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有如下代码:
    (随便写的,不要在乎 script 节点的意义,做位置参照而已)

    import lxml.html
    import lxml.etree
    
    text = '''
    <html>
        <body>
            <div>
                <p>我不是你需要的文本</p>
            </div>
            <div>
                <script type="text/javascript">
                    console.log("Hello world")
                </script>
                <p>我是你需要的文本</p>
            </div>
        </body>
    </html>
    '''
    
    doc = lxml.html.fromstring(text)
    body = doc.xpath("/html/body")[0]
    divs = body.xpath("div")
    for div in divs:
        scripts = div.xpath("script[@type=\"text/javascript\"]")
        if scripts is not None:
            ps = div.xpath("p")
            p = ps[0]
            print(p.text)
    

    本意是通过 scripts is not None 匹配到第二个 div 节点,但意外的是两个 div 均匹配成功
    如果输出 scripts,还都会得到 script 节点

    8 条回复    2017-08-12 13:02:10 +08:00
    misaka19000
        1
    misaka19000  
       2017-08-11 11:52:35 +08:00 via Android
    script 前面加个./
    anguslg
        2
    anguslg  
       2017-08-11 12:16:02 +08:00
    [] != None

    所以两个 p 都被选取到了
    syncher
        3
    syncher  
       2017-08-11 12:18:23 +08:00 via Android
    可以试试 xpath helper 插件
    wencan
        4
    wencan  
    OP
       2017-08-11 12:40:59 +08:00 via Android
    @anguslg
    多谢
    忘了 not found 返回的是[]
    有个方法 not found 返回 None,结果记混淆了
    mckelvin
        5
    mckelvin  
       2017-08-11 12:45:24 +08:00
    wencan
        6
    wencan  
    OP
       2017-08-11 14:55:56 +08:00
    @anguslg @misaka19000
    谢谢两位
    最终代码:
    ```
    if td.xpath(".//script[@type=\"text/javascript\"]"):
    pass
    ```
    anguslg
        7
    anguslg  
       2017-08-11 21:02:36 +08:00
    @wencan 把最外面两个双引号改成单引号,可以不用写转义符号了
    wencan
        8
    wencan  
    OP
       2017-08-12 13:02:10 +08:00
    @anguslg 习惯了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2803 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 13:15 · PVG 21:15 · LAX 06:15 · JFK 09:15
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.