美文网首页
XPath学习

XPath学习

作者: 半大人 | 来源:发表于2019-08-20 16:01 被阅读0次

    扩展资料:XPath语法

    示例代码

    #定义一个html源码字符串
    html='''
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <bookstore>
    <book>
      <title lang="ENG">Harry Potter</title>
      <price>29.99</price>
    </book>
    <book>
      <title lang="CN">学习使我疯狂</title>
      <price>39.95</price>
    </book>
    </bookstore>
    '''
    
    from lxml import etree#用来解析网页的
    parse=etree.HTML(html,etree.HTMLParser())#导入网页给解析器
    #定位
    parse.xpath('//book') #选取所有 book 子元素,而不管它们在文档中的位置。
    parse.xpath('//book[1]/title/@lang')#选取第一个book节点的子节点title名为 lang的属性。
    parse.xpath("//title[@lang]")#选取所有 title 元素,且这些元素拥有lang 属性。
    parse.xpath("//title[@lang='ENG']")#选取所有 title 元素,且这些元素拥有值为 eng 的 lang 属性。
    #取值
    parse.xpath('//book[1]/title/@lang')#选取第一个book节点的子节点title的名为lang属性的属性值。
    parse.xpath('//book[1]/title/text()')#选取第一个book节点的子节点title的文本值。
    
    child=parse.xpath('//book[1]/title')#选取第一个book节点的子节点title#返回的值,是一个列表
    text=child[0].xpath('text()')#获取该节点的文本
    lang=child[0].xpath('@lang')#获取该节点的lang属性值
    #打印text lang
    print(text)
    print(lang)
    

    相关文章

      网友评论

          本文标题:XPath学习

          本文链接:https://www.haomeiwen.com/subject/lbffqctx.html