您当前的位置: 首页 >  爬虫

34 爬虫 - XPath实例测试

杨林伟 发布时间:2019-08-29 17:52:39 ,浏览量:1

1. 获取所有的
  • 标签
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    print type(html)  # 显示etree.parse() 返回类型
    
    result = html.xpath('//li')
    
    print result  # 打印
  • 标签的元素集合 print len(result) print type(result) print type(result[0])
  • 输出结果:

    
    [, , , , ]
    5
    
    
    
    2. 继续获取
  • 标签的所有 class属性
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    result = html.xpath('//li/@class')
    
    print result
    

    运行结果:

    ['item-0', 'item-1', 'item-inactive', 'item-1', 'item-0']
    
    3. 继续获取
  • 标签下hrelink1.html标签
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    result = html.xpath('//li/a[@href="link1.html"]')
    
    print result
    

    运行结果

    []
    
    4. 获取
  • 标签下的所有 标签
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    
    #result = html.xpath('//li/span')
    #注意这么写是不对的:
    #因为 / 是用来获取子元素的,而  并不是 
  • 的子元素,所以,要用双斜杠 result = html.xpath('//li//span') print result
  • 运行结果

    []
    
    5. 获取
  • 标签下的标签里的所有 class
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    result = html.xpath('//li/a//@class')
    
    print result
    

    运行结果

    ['blod']
    
    6. 获取最后一个
  • 的 href
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    
    result = html.xpath('//li[last()]/a/@href')
    # 谓语 [last()] 可以找到最后一个元素
    
    print result
    

    运行结果

    ['link5.html']
    
    7. 获取倒数第二个元素的内容
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    result = html.xpath('//li[last()-1]/a')
    
    # text 方法可以获取元素内容
    print result[0].text
    

    运行结果

    fourth item
    
    8. 获取 class 值为 bold 的标签名
    # xpath_li.py
    
    from lxml import etree
    
    html = etree.parse('hello.html')
    
    result = html.xpath('//*[@class="bold"]')
    
    # tag方法可以获取标签名
    print result[0].tag
    

    运行结果

    span
    
  • 关注
    打赏
    1688896170
    查看更多评论

    杨林伟

    暂无认证

    • 1浏览

      0关注

      3183博文

      0收益

    • 0浏览

      0点赞

      0打赏

      0留言

    私信
    关注
    热门博文
    立即登录/注册

    微信扫码登录

    0.0679s