3

馬鹿げている。Pythonとxpathの初心者はこちら。'Open Box Price: $1079.99'xpathを使用して完全なテキストを抽出しようとしています

<div class="prod-price">
<p class="opbox-price">
    <strong> Open Box Price:<br>$1079.99</strong>
    </p>
<p class="orig-price">
    Regular Price: <strong>$1499.98</strong>
    </p>
</div>

しかし、私はできません。テキストはで停止し<br>ます。これが私のコードです

doc = lxml.html.fromstring(r.content)
elements = doc.xpath(item_xpath)
print elements[1].find('div[3]/p[1]/text()[normalize-space()]')
4

2 に答える 2

3

必要なXPathの基本は、使用descendant-or-selfすることです。結果を必要に応じて微調整します。

>>> doc.xpath('//p[1]/descendant-or-self::text()')
['\n    ', ' Open Box Price:', '$1079.99', '\n    ']
>>> doc.xpath('//p[2]/descendant-or-self::text()')
['\n    Regular Price: ', '$1499.98', '\n    ']

またはあなたがしているようにlxml.html、あなたは使うことができますtext_content()

paras = doc.xpath('//p'): # or findall etc...
for para in paras:
    print para.text_content()
于 2012-10-18T23:07:29.873 に答える
1

div初期コンテキスト(現在のノード)が:の親であると仮定して、使用するだけです。

normalize-space(div/p[1]/strong)

XSLTベースの検証

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output method="text"/>

 <xsl:template match="/*">
     "<xsl:value-of select="normalize-space(div/p[1]/strong)"/>"
 </xsl:template>
</xsl:stylesheet>

この変換が次のXMLドキュメントに適用された場合(提供されたドキュメントは、整形式に修正されてから、最上位のhtml要素で囲まれます)。

<html>
    <div class="prod-price">
        <p class="opbox-price">
          <strong> Open Box Price:<br />$1079.99</strong>
        </p>
        <p class="orig-price">
    Regular Price: 
            <strong>$1499.98</strong>
        </p>
    </div>
</html>

XPath式は最上位の要素(html)から評価され、評価の結果が出力にコピーされます(引用符で囲まれます)

"Open Box Price:$1079.99"
于 2012-10-18T23:36:01.230 に答える