xpath expression to remove whitespace

前端 未结 6 1977
野性不改
野性不改 2020-12-08 00:18

I have this HTML:

 
   
     

        
6条回答
  •  执念已碎
    2020-12-08 00:45

    I came across this thread when I was having my own issue similar to above.

    HTML

    XPath start command

    tree.xpath('//div[@class="d-flex"]/h4/a/text()')
    

    However this grabbed random whitespace and gave me the output of:

    ['\n          ', '\n        1.0.1\n      ']
    

    Using normalize-space, it removed the first blank space node and left me with just what I wanted

    tree.xpath('//div[@class="d-flex"]/h4/a/text()[normalize-space()]')
    
    ['\n        1.0.1\n      ']
    

    I could then grab the first element of the list, and use strip() to remove any further whitespace

    XPath final command

    tree.xpath('//div[@class="d-flex"]/h4/a/text()[normalize-space()]')[0].strip()
    

    Which left me with exactly what I required:

    1.0.1
    

提交回复
热议问题