xpath中沒有提供對class的原生查找方法。但是 stackoverflow 看到了一個很有才的回答:
This selector should work but will be more efficient if you replace it with your suited markup:
這個表達式應該是可行的。不過如果你把class換成更好識別的標識執行效率會更高
//*[contains(@class, 'Test')]
But since this will also match cases like class="Testvalue" or class="newTest".
但是這個表達式會把類似 class="Testvalue" 或者 class="newTest"也匹配出來。
//*[contains(concat(' ', @class, ' '), ' Test ')]
If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry)
如果您希望確定它能夠正確匹配,則還可以使用 normalize-space 函數清除類名周圍的空白字符(如@Terry所述)
//*[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]
Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.
請注意在所有這些版本里,除非你想要在所有元素里搜索帶有這些條件的元素,否則你最好把*號替換成你想要匹配的具體的元素名(標簽名)。
具體來講大概就是這樣:
html = """ <div class="view_fields"> <div class="row view_row"> <!-- row header --> <div class="view_field col-xs-4 col-sm-5 col-md-4">Organization </div> <!-- row value --> <div class="view_value col-xs-8 col-sm-7 col-md-8"> <a href="/org/14607">INTERNET HARBOR</a> </div> </div> </div> """ items = response.xpath('//div[contains(@class,"view_fields")]')
相反:不包含指定的屬性或值
如果查找某個屬性值是否包含或不包含指定的屬性或值時:結合Xpath路徑來提取循環列表中的一個HTML標簽的InnerText,提取的時候需要判斷是這個標簽的class屬性是否包含某個指定的屬性值,利用Xpath的contains可以解決,代碼如下:
//選擇不包含class屬性的節點 var result = node.SelectNodes(".//span[not(@class)]"); //選擇不包含class和id屬性的節點 var result = node.SelectNodes(".//span[not(@class) and not(@id)]"); //選擇不包含class="expire"的span var result = node.SelectNodes(".//span[not(contains(@class,'expire'))]"); //選擇包含class="expire"的span var result = node.SelectNodes(".//span[contains(@class,'expire')]");
查詢值為空的節點
xml.xpath("//[XX[.!='']]")
--------------------------------------//td[.!= '']---------------------------------------------------------------- if each.xpath("./td[2]/text()[.!= '']"): self.positionType = each.xpath("./td[2]/text()").extract()[0] else: self.positionType = "未知"