刮板给空白输出

问题描述 投票:1回答:2

我在我的python脚本中使用了一个选择器来从下面给出的一些html元素中获取文本。我尝试用.text从元素中获取Shop here cheap字符串,但它根本不起作用。但是,当我尝试使用.text_content()时,它可以正常工作。

我的问题是:

.text方法有什么问题?为什么它不能解析元素中的文本?

Html元素:

<div class="Price__container">
    <span class="ProductPrice" itemprop="price">$6.35</span>
    <span class="ProductPrice_original">$6.70</span>
    Shop here cheap
</div>

我试过的:

from lxml import html

tree = html.fromstring(element)
for data in tree.cssselect(".Price__container"):      
    print(data.text)           #It doesn't work at all

顺便说一句,我不想​​继续使用.text_content(),这就是为什么我期待任何答案来使用.text代替文本。提前致谢。

python python-3.x web-scraping css-selectors
2个回答
1
投票

我认为混淆的根本原因是lxml有这个代表节点内容的.text&.tail concept,它避免了必须有一个特殊的“文本”节点实体,引用documentation

两个属性.text和.tail足以表示XML文档中的任何文本内容。这样,除了Element类之外,ElementTree API不需要任何特殊的文本节点,这些节点往往会相当频繁(正如您可能从经典DOM API中获知)。

在您的情况下,Shop here cheap<span class="ProductPrice_original">$6.70</span>元素的尾部,因此不包含在父节点的.text值中。

除了.text_content()之外的其他方法,您可以通过非递归获取所有顶级文本节点来达到尾部:

print(''.join(data.xpath("./text()")).strip())

或者,获取最后一个顶级文本节点:

print(data.xpath("./text()[last()]")[0].strip())

0
投票

另一种方法可能是打击:

content="""
<div class="Price__container">
    <span class="ProductPrice" itemprop="price">$6.35</span>
    <span class="ProductPrice_original">$6.70</span>
    Shop here cheap
</div>
"""
from lxml import html

tree = html.fromstring(content)
for data in tree.cssselect(".Price__container"):
    for item in data:item.drop_tree()
    print(data.text.strip())

输出:

Shop here cheap
© www.soinside.com 2019 - 2024. All rights reserved.