Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.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
Python xpath提取特定节点中的所有文本,并使用scrapy将其作为一个元素返回_Python_Xpath_Scrapy - Fatal编程技术网

Python xpath提取特定节点中的所有文本,并使用scrapy将其作为一个元素返回

Python xpath提取特定节点中的所有文本,并使用scrapy将其作为一个元素返回,python,xpath,scrapy,Python,Xpath,Scrapy,所以我有这个html: <html> <p> This is my first sentence <br> This sentance should be considered as part of the first one. <br> And this also </p> <p> This is the second sentence </p> </html>

所以我有这个html:

<html>
<p>
   This is my first sentence
   <br>
   This sentance should be considered as part of the first one.
   <br>
   And this also
</p>
<p>
   This is the second sentence
</p>
</html>
我得到的结果是:

[
'This is my first sentence',
'This sentance should be considered as part of the first one.'
'And this also'
'This is the second sentence'
]
我想要的输出:

[
 'This is my first sentence This sentance should be considered as part of the first one And this also'
 'This is the second sentence'
]
有关于如何使用xpath表达式解决此问题的帮助吗


非常感谢:)

这解决了问题

from w3lib.html import remove_tags
two_texts = response.xpath('//p').extract()
two_texts = [remove_tags(text) for text in two_texts]

这解决了问题

from w3lib.html import remove_tags
two_texts = response.xpath('//p').extract()
two_texts = [remove_tags(text) for text in two_texts]

或者,您可以使用注释中建议的
'.join()
避免使用
w3lib

parations=response.css('p')
段落=[''.join(p.xpath('./text()).getall())表示段落中的p]

或者,您可以使用
'.join()
避免使用
w3lib
,如注释中所示:

parations=response.css('p')
段落=[''.join(p.xpath('./text()).getall())表示段落中的p]

能否将列表项加入从respose.xpath返回的列表中?“”.join(list_中的x代表x从_xpath返回_)实际上这对我来说是不可能的,我需要使用xpath解决它,因为我有很多p元素,每个元素都有一些我不知道的文本,还有一些原因。如果有一个使用xpath的解决方案会更好。Scrapy只支持xpath-1.0。但这只能通过XPath-2.0或更高版本来解决。因此,如果不在Python级别执行此操作,我怀疑您是否能找到解决方案。@zx485非常感谢,然后我将进入更高的级别,如
//p
,然后获取所有html并清理它以获得最终文本。请添加您的评论作为此问题的答案。如果您可以扩展示例XML,以包括为什么先选择段落不适合您的原因,那将是非常好的。也许有人能想出一个很好的解决方案,考虑到您在评论中提到的这些限制。您能将列表项加入从respose.xpath返回的列表中吗?“”.join(list_中的x代表x从_xpath返回_)实际上这对我来说是不可能的,我需要使用xpath解决它,因为我有很多p元素,每个元素都有一些我不知道的文本,还有一些原因。如果有一个使用xpath的解决方案会更好。Scrapy只支持xpath-1.0。但这只能通过XPath-2.0或更高版本来解决。因此,如果不在Python级别执行此操作,我怀疑您是否能找到解决方案。@zx485非常感谢,然后我将进入更高的级别,如
//p
,然后获取所有html并清理它以获得最终文本。请添加您的评论作为此问题的答案。如果您可以扩展示例XML,以包括为什么先选择段落不适合您的原因,那将是非常好的。也许有人能想出一个很好的解决方案,考虑到你在评论中提到的那些限制。我尝试了你的解决方案,效果很好,但仍然需要清理html标记(+1)我尝试了你的解决方案,效果很好,但仍然需要清理html标记(+1)