2013-04-26 58 views
1

我試圖分裂以下標籤:Python的分裂字符串索引超出範圍

<h3><a href="#AC Adapter" onclick="getProductsBasedOnCategoryID('Asus','AC Adapter','ET1611PUT','6941', this, 'E Series')">AC Adapter 

      </a></h3> 

使用下面的代碼:

print "FETCHING CATEGORY" 
    atag = s.h3 
    for data in atag: 
     while getattr(atag, 'name', None) != 'h3': 
      atag = atag.nextSibling 
     atag.a 
     atag = literal_eval('(' + atag.nextSibling.replace(', this', '').split('(', 1)[1]) 
     print atag 

不過,我得到以下錯誤:

File "//CPSBS/RedirectedFolders/aysha/My Documents/asus_tables(edited) a tags.py", line 84, in <module> 
    atag = literal_eval('(' + atag.nextSibling.replace(', this', '').split('(', 1)[1]) 
IndexError: list index out of range 

我猜我有什麼問題嗎?此a標記有一個onclick屬性,我想訪問,所以我將如何輸入到下面的代碼?

這裏是我從

http://www.asusparts.eu/partfinder/Asus/All解析數據,在一/ E系列

網址

[編輯]

導航樹我想從

檢索數據
<div id="accordion" class="ui-accordion ui-widget ui-helper-reset ui-accordion-icons" style="width: 760px;" role="tablist"> 
    <h3 class="ui-accordion-header ui-helper-reset ui-state-active ui-corner-top" role="tab" aria-expanded="true" aria-selected="true" tabindex="0"> 
     <span class="ui-icon ui-icon-triangle-1-s"></span> 
     <a onclick="getProductsBasedOnCategoryID('Asus','AC Adapter','ET10B','6941', this, 'E Series')" href="#AC Adapter" tabindex="-1" loaded="Loaded">AC Adapter </a> 
    </h3> 
    <div id="6941" class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content-active" role="tabpanel" style="display: block;"> 
     <table class="productTableList"> 
      <tbody> 
     </table> 
     <table class="productTableList"> 
      <tbody> 
       <tr style="height:90px;background-color:#ebf4ff;"> 
        <td class="ProduktLista" width="70px"> 
        <td class="ProduktLista" width="315"> 
         <a onclick="getProductInformationModal("Asus","14G110008340");"> 
         <br> 
+0

而不是我們顯示的錯誤,因爲我們可能可以運行的代碼,爲什麼不打破這個eval到多個單獨的行,檢查什麼是從''split''。如果你先嚐試一下,它可能會有所幫助。或者至少張貼你在做完之後得到的東西。 – CppLearner 2013-04-26 08:58:47

回答

1

當您遇到這些類型的問題時,您無法立即看到問題所在是的,那麼你需要劃分複雜的表達式。相反的:

atag = literal_eval('(' + atag.nextSibling.replace(', this', '').split('(', 1)[1]) 

它重寫(你當然應該使用的變量名更有意義):

nextSibling = atag.nextSibling 
txt1 = nextSibling.replace(', this', '') 
split = txt1.split('(', 1) 
txt2 = split[1] 
txt3 = '(' + txt2 
atag = literal_eval(txt3) 

這將讓你哪裏出了問題存在的確切表達,和所涉及的值的打印聲明應該給你的答案..

+0

它不打印任何東西:/我編輯我的帖子上面,並添加了導航樹的HTML片段 – ash 2013-04-26 09:51:40

相關問題