2011-08-29 22 views
0

我不認爲我瞭解如何檢查數組索引存在...快譯通指數在BeautifulSoup和「如果x在快譯通」

for tag in soup.findAll("input"): 
      print tag['type'] 
      if 'type' in tag: 
       print "b" 

輸出:

2255 
text 
hidden 
text 
text 
text 
Traceback (most recent call last): 
    File "/home//workspace//src/x.py", line 268, in <module> 
    print tag['type'] 
    File "/home//workspace//src/BeautifulSoup.py", line 601, in __getitem__ 
    return self._getAttrMap()[key] 
KeyError: 'type' 

爲什麼它不會輸出'b'?

回答

2

A BeautifulSoup Tag不是dict。有時它在某些方面表現得像一個(你發現的[]表示法獲得一個屬性的值),但在其他方面它沒有。 Tag上的in將檢查標籤是否是該標籤的直接子項;它不檢查屬性。

相反,你可以做這樣的事情:

if not tag.get('type', None): 
    pass # type is empty or nonexistent 
1

爲什麼不輸出 'B' 永遠不會消失?

你假設從findAll返回的標籤是dicts,實際上它們不是。您使用的BeautifulSoup庫具有自己的自定義類,在這種情況下,BeautifulSoup.Tag可能類似於字典,但不是。

這裏,檢查了這一點:

 
    >>> doc = ['<html><head><title>Page title</title></head>', 
    ...  '<body><p id="firstpara" align="center">This is paragraph <b>one</b>.', 
    ...  '<p id="secondpara" align="blah">This is paragraph <b>two</b>.', 
    ...  '</html>'] 
    >>> soup = BeautifulSoup(''.join(doc)) 
    >>> tag = soup.findAll("p")[0] 
    >>> type(tag) 
    class 'BeautifulSoup.Tag'> 
    >>> isinstance(tag, dict) 
    False 

因爲它不是真正的字典,你得到一些不同的(特定領域的)行爲,在這種情況下,直接孩子的列表(標籤直接包含的內您正在「索引」的標籤)。

它看起來像你想知道,如果輸入標籤有一個屬性,所以要根據BeautifulSoup文檔,你可以列出使用tag.attrs和attrMap標籤的屬性。

 
    >>> tag.attrs 
    [(u'id', u'firstpara'), (u'align', u'center')] 
    >>> tag.attrMap 
    {u'align': u'center', u'id': u'firstpara'} 
    >>> 'id' in tag.attrMap 
    True 

BeautifulSoup是一個真正有用的庫,但它是一個你有一個位打得到你想要的結果。確保花時間在與類一起玩的交互式控制檯中,並記住使用幫助(someobject)語法來查看你在玩什麼以及它有什麼方法。