作者lexus7310 (Fox)
看板Python
標題[問題] 有關HTMLParser
時間Thu Nov 9 00:04:21 2017
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
→ stucode: attrs == [('target', '_blank')] 會找到「只有」 11/09 01:16
→ stucode: target="_blank" 屬性的元素。一直不成立表示該頁面沒有 11/09 01:17
→ stucode: 符合這個條件的元素。如果想找所有包含該屬性的元素, 11/09 01:17
→ stucode: 請用 ('target', '_blank') in attrs。 11/09 01:17
→ lexus7310: 懂了 感謝 11/09 22:53