2015-02-24 52 views
-2

我有一個python代碼從表中提取一些信息。但事情有時是Xpath的變化。現在,它只有兩個不同的XPath的,看起來像這樣之間的變化:是否有無論如何檢查給定的XPath在Python中是否有效?

//*[@id='content-primary']/table[3]/tbody/tr[td[1]/span/span/ 

和另一種方法是在表像這樣的微小變化:

//*[@id='content-primary']/table[2]/tbody/tr[td[1]/span/span/ 

這是我使用的代碼現在得到我需要的信息:

rows_xpath = XPath("//*[@id='content-primary']/table[3]/tbody/tr[td[1]/span/span//text()='%s']" % (date)) 

所以我想要做的是檢查給定的XPath是否有效。如果不是,我只是嘗試其他XPath替代方案。

希望有人能幫助我解決這個問題。謝謝你們。

EDIT1

<table class="clCommonGrid" cellspacing="0"> 
      <thead> 
       <tr> 
        <td colspan="3">Kommande matcher</td> 
       </tr> 
       <tr> 
        <th style="width:1%;">Tid</th> 
        <th style="width:69%;">Match</th> 
        <th style="width:30%;">Arena</th> 
       </tr> 
      </thead> 
      <tfoot> 
      <tr> 
       <td colspan="3"> 
        <dl> 
         <dt class="clNotify">Röd text</dt> 
         <dd> = Ändrad matchtid&nbsp;</dd> 
         <dt><img src="http://svenskfotboll.se/i/u/alert.gif" alt="Röda utropstecknet" /></dt> 
         <dd> = Peka på utropstecknet så visas en notering&nbsp;</dd> 
         <dt><img src="http://svenskfotboll.se/i/widget.gif" alt="Widget" /></dt> 
         <dd><a href="http://gbgfotboll.se/widgets/?scr=cominginleague&amp;ftid=57109">Hämta widget för kommande matcher</a></dd> 
        </dl> 
       </td> 
      </tr> 
     </tfoot> 
      <tbody class="clGrid"> 

     <tr class="clTrOdd"> 
      <td nowrap="nowrap" class="no-line-through"> 
       <span class="matchTid"><span>2015-04-17<!-- br ok --> 19:15</span></span> //This is the date i am checking with first 



      </td> 
      <td><a href="?scr=result&amp;fmid=2928398">Götene IF - Vårgårda IK </a></td> // The other information that i need from the table later 
      <td><a href="?scr=venue&amp;faid=16484">Sparbanksvallen Götene konstgräs </a> </td> 
     </tr> 
+1

這[解決] [1]可能會幫助你。在例外情況下,您可以嘗試其他文件。 [1]:http://stackoverflow.com/questions/22889021/valid-xpath-expression – Vijay 2015-02-24 21:53:23

+0

你是什麼意思與文件? @Vijay – 2015-02-24 21:57:46

+1

我建議構建單個XPath,更多依賴於節點屬性值(id,class,.etc),而不是有2個XPaths依賴於節點positons ... – har07 2015-02-25 00:12:56

回答

0

在我的情況,我並不需要指定要提取信息的表。因爲,我將得到的是隻包含在該表的日期指定的信息我只是用這個代碼和它的工作對我罰款:

**rows_xpath = XPath("//*[@id='content-primary']/table/tbody/tr[td[1]/span/span//text()='%s']" % (date))** 

現在是這意味着它會經過雙方只是表網站中的表格。它不是一個乾淨的解決方案,但爲我工作..

+0

正是我需要的,謝謝! – 2015-02-28 12:16:21