Python 我做错了什么?使用lxml解析HTML

Python 我做错了什么?使用lxml解析HTML,python,html,lxml,Python,Html,Lxml,我正在尝试使用lxml解析网页,但在尝试返回一个div中的所有文本元素时遇到了问题。以下是我到目前为止得到的结果 import requests from lxml import html page = requests.get("https://www.goodeggs.com/sfbay/missionheirloom/seasonal-chicken-stew-16oz/53c68de974e06f020000073f",verify=False) tree = html.fromstri

我正在尝试使用lxml解析网页,但在尝试返回一个div中的所有文本元素时遇到了问题。以下是我到目前为止得到的结果

import requests
from lxml import html
page = requests.get("https://www.goodeggs.com/sfbay/missionheirloom/seasonal-chicken-stew-16oz/53c68de974e06f020000073f",verify=False)
tree = html.fromstring(page.text)
foo = tree.xpath('//section[@class="product-description"]/div[@class="description-body"]/text()')
现在,“foo”返回一个空列表[]。其他页面会返回一些内容,但不是
中标签中的所有内容。其他页面返回所有内容,因为它位于div的顶层

如何恢复该div中的所有文本内容?
谢谢

我认为XPath表达式应该是:

//section[@class="product-description"]/div[@class="description-body"]//text()

UPD。正如上面@unutbu所指出的,表达式将以列表的形式获取文本节点,所以您必须对它们进行循环。如果您需要将整个文本内容作为一个文本项,请检查unutbu的答案以了解其他选项。

文本位于两个
标记内,因此部分文本位于每个
p.text
中,而不是
div.text
中。但是,您可以通过调用该方法而不是使用XPath
text()
,来提取
的所有子级中的所有文本:

屈服

We’re super excited about the changing seasons! Because the new season brings wonderful new ingredients, we’ll be changing the flavor profile of our stews. Starting with deliveries on Thursday October 9th, the Chicken and Wild Rice stew will be replaced with a Classic Chicken Stew. We’re sure you’ll love it!Mission: Heirloom is a food company based in Berkeley. All of our food is sourced as locally as possible and 100% organic or biodynamic. We never cook with refined oils, and our food is always gluten-free, grain-free, soy-free, peanut-free, legume-free, and added sugar-free.

另外,dfsq已经建议使用XPath
..//text()
。这同样有效,但与
text\u content
不同,文本片段作为单独的项目返回:

In [256]: root = LH.fromstring('<a>FOO <b>BAR <c>QUX</c> </b> BAZ</a>')

In [257]: root.xpath('//a//text()')
Out[257]: ['FOO ', 'BAR ', 'QUX', ' ', ' BAZ']

In [258]: [a.text_content() for a in root.xpath('//a')]
Out[258]: ['FOO BAR QUX  BAZ']
[256]中的
:root=LH.fromstring('FOO-BAR-qx-BAZ'))
[257]中的root.xpath(“//a//text()”)
Out[257]:[FOO',BAR',QUX','BAZ']
[258]中:[a.text_content()表示根.xpath('//a')中的
Out[258]:['FOO-BAR-QUX-BAZ']

是的,这正是我需要的!谢谢//text()方法可以工作,但获取列表中的元素不适用于我的用例。
In [256]: root = LH.fromstring('<a>FOO <b>BAR <c>QUX</c> </b> BAZ</a>')

In [257]: root.xpath('//a//text()')
Out[257]: ['FOO ', 'BAR ', 'QUX', ' ', ' BAZ']

In [258]: [a.text_content() for a in root.xpath('//a')]
Out[258]: ['FOO BAR QUX  BAZ']