Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
XPath使用超链接获取文本(Python)_Python_Html_Xpath_Lxml - Fatal编程技术网

XPath使用超链接获取文本(Python)

XPath使用超链接获取文本(Python),python,html,xpath,lxml,Python,Html,Xpath,Lxml,我在使用XPath方面是新手(一般来说,我是Python的相对初学者)。我试着从维基百科页面的第一段中取出文本来浏览 以Python页面()为例 如果我把它放入一个变量中 page = requests.get("https://en.wikipedia.org/wiki/Python_(programming_language)") tree = html.fromstring(page.content) first = tree.xpath("/html/body/div[3]/div[3

我在使用XPath方面是新手(一般来说,我是Python的相对初学者)。我试着从维基百科页面的第一段中取出文本来浏览

以Python页面()为例

如果我把它放入一个变量中

page = requests.get("https://en.wikipedia.org/wiki/Python_(programming_language)")
tree = html.fromstring(page.content)
first = tree.xpath("/html/body/div[3]/div[3]/div[4]/div/p[1]/text()")
然后我知道所需的段落位于XPath
/html/body/div[3]/div[3]/div[4]/div/p[1]

所以我把文本转换成一个变量

page = requests.get("https://en.wikipedia.org/wiki/Python_(programming_language)")
tree = html.fromstring(page.content)
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']

如您所见,我缺少web链接中的单词/句子。

链接本身就是您需要删除的节点

/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\u content()
    检索文本,包括所有子节点