2015-04-03 88 views
0
def handle_starttag(self, tag, attrs): 
    print(attrs) 

[] 

我的attrs怎麼是空列表?標籤內的數據在哪裏? 我不知道爲什麼我的attrs是空的,我需要將數據從它,無論是從handle_data或從ATTRSPython 3 - HTML解析器 - 空屬性

import urllib.request 
 
from html.parser import HTMLParser 
 
import sys 
 

 
class myHTMLParser(HTMLParser): 
 
    
 
    def __init__(self): 
 
     HTMLParser.__init__(self) 
 
     self.country = {} 
 
     
 
    def handle_starttag(self, tag, attrs): 
 
     if tag == 'currency_name': 
 
      self.country[self.handle_data] = tag 
 
     print(self.country) 
 
     
 
    def handle_endtag(self, tag): 
 
     pass 
 
    
 
    def handle_data(self, data): 
 
     return(data.strip()) 
 
    
 
def main(): 
 
    if len(sys.argv) > 1: 
 
     link = sys.argv[1] 
 
    else: 
 
     link = 'http://www.bankofcanada.ca/stats/assets/xml/noon-five-day.xml' 
 
     
 
     
 
    myparser = myHTMLParser()  
 
    file = open(link, 'r') 
 
    html = file.read() 
 
    myparser.feed(html) 
 
    file.close() 
 
main()

回答

1

我想你感到困惑。至少程序中的URL沒有屬性,但它確實有數據。屬性是標籤本身內部的信息。這是傳遞信息的一種方式。

對於您的頁面,信息介於開始標記和結束標記之間。

<a href="mysite.org"></a>是一種傳遞信息的方式。

<p>this is text</p> 

是另一個。

由於沒有屬性,該列表爲空。數據位於handle_data返回的結果中。