2010-04-14 36 views
11

我想用lxml使用XPath表達式解析HTML。我的問題是匹配對一個標籤的內容:如何匹配XPath中的元素內容(lxml)?

例如給定的使用

.//a[@href='http://something'] 

<a href="http://something">Example</a> 

元件我可以匹配href屬性,但給出的表達式

.//a[.='Example'] 

或甚至

.//a[contains(.,'Example')] 

lxml拋出'invalid node predicate'異常。

我在做什麼錯?

編輯:

示例代碼:

from lxml import etree 
from cStringIO import StringIO 

html = '<a href="http://something">Example</a>' 
parser = etree.HTMLParser() 
tree = etree.parse(StringIO(html), parser) 

print tree.find(".//a[text()='Example']").tag 

預期輸出爲 'a'。我得到 '語法錯誤:無效的節點謂詞'

+2

而不是使用StringIO的,你也可以使用etree.fromstring()來解析您的HTML。 – 2011-08-04 07:09:54

回答

18

我會嘗試使用:使用XPath

.//a[text()='Example']

()方法:

tree.xpath(".//a[text()='Example']")[0].tag 

如果您想情況下使用iterfind() ,findall(),find(),findtext(),請記住,值比較和函數等高級功能在ElementPath中不可用。

lxml.etree supports the simple path syntax of the find, findall and findtext methods on ElementTree and Element, as known from the original ElementTree library (ElementPath). As an lxml specific extension, these classes also provide an xpath() method that supports expressions in the complete XPath syntax, as well as custom extension functions.

+0

我不想根據href找到鏈接,但基於它包含的文本:上例中的「示例」:) .//a[@href='http://something']工程它的方式... – akosch 2010-04-14 13:59:27

+1

你需要刪除= .//a[text()='示例'] – Greg 2010-04-14 14:20:06

+0

感謝您的建議,但是這個提出了「SyntaxError:invalid node predicate」 – akosch 2010-04-14 14:20:25

相關問題