2017-07-27 110 views
0

經過多次搜索和修改後,我仍然無法弄清楚。它在列表中的第19位停止。無法在Python中迭代列表3

這是錯誤:

line 22 in <module> parent_td=[td for td in possible_tds if 'Product' in td.text][0] 
Index Error: List index out of range 

from urllib.request import urlopen as uReq 
    from urllib.request import Request 
    from bs4 import BeautifulSoup as soup 
    import re 

    ListName = "list" 
    OpenList = open(ListName,"r") 
    n=int(OpenList.readline()) 

    for num in range(1,n+1): 
     print(num) 
     theList=OpenList.readline() 

     AccessCME=Request(theList,headers={"User-Agent":"Mozilla/5.0"}) 
     CMEPage=uReq(AccessCME).read() 

     page_soup=soup(CMEPage,"html.parser") 
     cme=page_soup.find("div",{"class":"cmeProduct section"}) 
     FuturesContracts=cme.span.text.strip() 

     possible_tds=page_soup.find_all('td',attrs={'class':"prodSpecAtribute"}) 
     parent_td=[td for td in possible_tds if 'Product' in td.text][0] 
     target = parent_td.fetchNextSiblings('td')[0].text.strip() 
     first_take=re.sub('CME Globex:\s', '', target) 
     BaseSymbol=re.sub(r'CME ClearPort:.*', '', first_take) 

     print(FuturesContracts, BaseSymbol) 

該鏈接列表文件:

https://drive.google.com/file/d/0BzzXkoIWuMAHWEhaQktrT3BKdG8/view?usp=sharing

讓我知道如果我需要澄清任何東西。歡迎提出改進/建議。

+3

在我看來,列表理解只是生成一個空列表。所以'possible_tds'中沒有'td',所以''Product''在'td.text'中。 –

+0

嗨,威廉,感謝您的解釋。但我對編碼非常陌生。你能擴展更多關於你在說什麼嗎? –

回答

1

您可能在您的列表理解中找不到任何候選人,最後會列出一個空白列表。

possible_tds=page_soup.find_all('td',attrs={'class':"prodSpecAtribute"}) 
parent_td_candidates = [td for td in possible_tds if 'Product' in td.text] 
if parent_td_candidates: 
    parent_td = parent_td_candidates[0] 
    # target = ... 
else: 
    print('No parent td candidates found! Is my data messed up or do I have a bug?') 
+0

嗨,哈里。我以爲我的上限是20。並有20個網站鏈接。所以我不知道你是如何知道它是一個空的列表。你能否更多地展開這個想法以及如何解決它? –

+0

我知道這是一個空的列表,因爲你的例外告訴了我。您的程序在唯一索引訪問爲索引0的行上拋出了「索引錯誤」。因此,列表的長度必須爲0. – Harrichael

+0

謝謝哈里。那麼如何修改我的代碼來解決它? –