2017-10-14 3 views
0

以下のhtml要素から、hi there!!のテキストを保持し、他のテキストを破棄するには、CSSセレクタを使用しますか?Catまた、.textまたは.text.strip()を使用しても結果が得られませんが、.text_content()を使用するとテキストが表示されます。セレクタを使用して特定のテキストを保持し、残りの部分を廃棄する

from lxml.html import fromstring 

html=""" 
<div id="item_type" data-attribute="item_type" class="ms-crm-Inline" aria-describe="item_type_c"> 
    <div> 
     <label for="item_type_outer" id="Type_outer"> 
      <div class="NotVisible">Cat</div> 
     Hi there!! 
      <div class="GradientMask"></div> 
     </label> 
    </div> 
</div> 
""" 
root = fromstring(html) 
for item in root.cssselect("#Type_outer"): 
    print(item.text) # doesn't work 
    print(item.text.strip()) # doesn't work 
    print(item.text_content()) # working one 

結果:

Cat 
Hi there!! 

はしかし、私は取得したい結果は、私が試しただけhi there!!とそのためのものですです:

root.cssselect("#Type_outer:not(.NotVisible)") #it doesn't work either 

、もう一度質問:

  1. なぜ.text_content()が仕事ですかしかし.textまたは.text.strip()はありませんか?
  2. 私はどのようにしてhi there!!をCSSセレクタで取得できますか? lxmlのツリーモデルで

答えて

1

、あなたが取得したいテキストは、クラスとdiv「NotVisible」のtailである:

>>> root = fromstring(html) 
>>> for item in root.cssselect("#Type_outer > div.NotVisible"): 
...  print(item.tail.strip()) 
... 
Hi there!! 

だから、最初の質問ではないだけでテキストノードを答えるために要素の前には、親のtextプロパティがあります。前の兄弟要素を持つテキストノードは、この質問のように、その要素のtailプロパティになります。

テキストを取得する別の方法は「こんにちは! labelの直接の子である空でないテキストノードに問い合わせることです。このような詳細レベルのクエリは、XPath式を使用して実行できます。

for item in root.cssselect("#Type_outer"): 
    print(item.xpath("text()[normalize-space()]")[0].strip()) 
+0

あなたはとても役に立ちます。一つの最後のこと:あなたがなぜ 'root.cssselect("#Type_outer:not(.NotVisible) ")'失敗したのか教えてください。私の無知を許しなさい。再度、感謝します。 – SIM

+1

この式では、クラス "NotVisible" *を持たないid "Type_outer"の* elementを選択します。この場合、基本的に同じIDを持つラベルには##Type_outerという同じ要素が返されますクラス "NotVisible" – har07

関連する問題