本文展示了如何使用Python的lxml库解析HTML,提取`<li>`元素的第二个`<code>children</code>`节点,并演示了去除多余空白字符的方法。重点在于DOM操作和字符串处理技巧。
- from lxml import etree
-
- html = """
- <ol>
- <li class="">直接选取<code>ul</code>的第二个<code>children</code></li>
- </ol>
- """
-
- data = etree.HTML(html)
- result = data.xpath('string(//ol/li)')
- print(result) # 直接选取ul的第二个children
- from lxml import etree
-
- # 如果li换行 则result结尾会有\n
- html = """
- <ol>
- <li class="">直接选取<code>ul</code>的第二个<code>children</code>
- </li>
- </ol>
- """
-
- data = etree.HTML(html)
- result = data.xpath('string(//ol/li)')
- print(result) # 直接选取ul的第二个children\n
- # 通过normalize-space去掉\n
- result = data.xpath('normalize-space(string(//ol/li))')
- print(result) # 直接选取ul的第二个children