首页 > 解决方案 > 从纯文本获取 Xpath

问题描述

我试图从文本而不是 URL 中获取 xpath。但我不断收到错误“AttributeError:'HtmlElement'对象没有属性'XPath'”

见下面的代码。

from lxml import html

var ='''<html lang="en">
  <head>
    <title>Selecting content on a web page with XPath</title>
  </head>
  <body>
     This is the body
  </body>
</html>
'''

tree = html.fromstring(var)

body = tree.XPath('//*/body')

print(body)

标签: pythonxpathlxml

解决方案


距离上一次使用 Python 已经 15 年了,但据我所知,它是一种区分大小写的语言,而且xpath方法都是小写的。

所以试试这个:

body = tree.xpath('//*/body')

推荐阅读