python 抓取文本结果,XPath通过超链接获取文本(Python)

I'm new at using XPath (and I'm a relative beginner at Python in general). I'm trying to take the text out of the first paragraph of a Wikipedia page through it.

if I get it into a variable

page = requests.get("https://en.wikipedia.org/wiki/Python_(programming_language)")

tree = html.fromstring(page.content)

Then I know the desired paragraph is on XPath /html/body/div[3]/div[3]/div[4]/div/p[1]

So I take that text into a variable

first = tree.xpath("/html/body/div[3]/div[3]/div[4]/div/p[1]/text()")

Resulting on this output

[' 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']

As you can see I'm missing the words/sentences that are inside of web links.

解决方案

Your XPath query matches the text child nodes of that node only. The text of the embedded live on another node and therefore excluded.

To descend use //text() as suggested; this will retrieve the text value of any descending node starting from the node in question.

/html/body/div[3]/div[3]/div[4]/div/p[1]//text()

Alternatively, you can select the node in question itself and retrieve the text using a parser method text_content() to retrieve the text including all child nodes.

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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值