[問題] 有關HTMLParser

看板Python作者 (Fox)時間8年前 (2017/11/09 00:04), 8年前編輯推噓0(005)
留言5則, 2人參與, 8年前最新討論串1/1
import urllib.request from html.parser import HTMLParser class MyHTMLParser(HTMLParser): #orverride方法來做條件判斷 def __init__(self): HTMLParser.__init__(self) self.isNumber= 0 self.list= [ ] def handle_data(self, data):#解析網頁資料 if self.isNumber== 1: #print('有資料') self.list.append(data) self.isNumber= 0 def handle_starttag(self, tag, attrs):#解析網頁起始標籤 if tag == 'a' and attrs == [('target','_blank')]: #print('有屬性') self.isNumber= 1 def handle_endtag(self, tag):#解析網頁結束標籤 pass data = urllib.request.urlopen('https://tw.yahoo.com/')#向網頁發出請求 content = data.read().decode('utf-8')#擷取網頁資料 data.close( )#關閉連線 #print(content) myparser = MyHTMLParser() myparser.feed(content)#feed()會依 HTML文件內標籤的順序依序處理 #print(myparser.list) print(myparser.list ,file=open('data.txt','w',encoding='utf-8'))#寫入data.txt' 程式碼如上,我想請問為何我在handle_starttag的function裡面 只要加上attrs == [('target','_blank')]的描述,我的if條件式就永遠不會成立,謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.160.203.167 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1510157064.A.FDD.html ※ 編輯: lexus7310 (1.160.203.167), 11/09/2017 00:06:36

11/09 01:16, 8年前 , 1F
attrs == [('target', '_blank')] 會找到「只有」
11/09 01:16, 1F

11/09 01:17, 8年前 , 2F
target="_blank" 屬性的元素。一直不成立表示該頁面沒有
11/09 01:17, 2F

11/09 01:17, 8年前 , 3F
符合這個條件的元素。如果想找所有包含該屬性的元素,
11/09 01:17, 3F

11/09 01:17, 8年前 , 4F
請用 ('target', '_blank') in attrs。
11/09 01:17, 4F

11/09 22:53, 8年前 , 5F
懂了 感謝
11/09 22:53, 5F
文章代碼(AID): #1Q0oi8_T (Python)