2017-04-23 28 views
-2

我想用一些庫將css選擇器轉換爲xpath。誰能給我解釋一下什麼是返回值的意思,我怎麼能覆蓋到的XPath像//div//*[[email protected]""]如何使用cssselector將css轉換爲xpath

from cssselect import GenericTranslator 

try 
    sel = CSSSelector('div.w3-container.top') 
except SelectorError: 
    print('Invalid selector.') 
print(sel) 

sel: 
'descendant-or-self::div[@class and contains(concat(\\' \\', normalize-space(@class), \\' \\'), \\' w3-container \\') and (@class and contains(concat(\\' \\', normalize-space(@class), \\' \\'), \\' top \\'))]' 
+1

這是xapth,不需要轉換。由於它以'descendant-or-self'開始,因此它希望您在要作爲搜索根目錄的節點上啓動查詢。你可以用'//'來獲得root權限。 – tdelaney

+0

發佈的代碼不起作用(CSSSelector未定義)。你可以更新一些對其他人有用的事情嗎? – tdelaney

回答

1

XPath(GenericTranslator().css_to_xpath('div.w3-container.top'))

這將返回給定的CSS類的XPath的

參觀此link更多詳情

+1

它已經是xpath ...這會創建一個'lxml' XPath對象,其中xpath是預解析的,如果多次使用,可能會更快。但沒有必要。 – tdelaney