我是 XPath 的新手(总的来说,我是 Python 的相对初学者)。我试图通过它从维基百科页面的第一段中取出文本。
以 Python 页面为例 (https://en.wikipedia.org/wiki/Python_(programming_language))
如果我把它放入变量
page = requests.get("https://en.wikipedia.org/wiki/Python_(programming_language)")
tree = html.fromstring(page.content)
然后我知道所需的段落在 XPath 上
/html/body/div[3]/div[3]/div[4]/div/p[1]
所以我将该文本放入变量中
first = tree.xpath("/html/body/div[3]/div[3]/div[4]/div/p[1]/text()")
产生此输出
[' is an ', ' ', ' for ', '. Created by ', ' and first released in 1991, Python has a design philosophy that emphasizes ', ', notably using ', '. It provides constructs that enable clear programming on both small and large scales.', '\n']
如您所见,我缺少网络链接中的单词/句子。
链接本身就是您需要下降的节点。
/html/body/div[3]/div[3]/div[4]/div/p[1]//text()
您的 XPath 查询仅匹配该节点的文本子节点。嵌入链接的文本位于另一个节点上,因此被排除在外。
要下降,请按照建议使用
//text()
;这将检索从相关节点开始的任何降序节点的文本值。
/html/body/div[3]/div[3]/div[4]/div/p[1]//text()
或者,您可以选择有问题的节点本身并使用解析器方法检索文本
text_content()
以检索包括所有子节点的文本。
lxml import html
import requests
page = requests.get('https://en.wikipedia.org/wiki/Python_(programming_language)')
tree = html.fromstring(page.content)
firstp = tree.xpath('/html/body/div[3]/div[3]/div[4]/div/p[1]')
firstp[0].text_content()