Re: [問題] 初學網路爬蟲問題

看板Python作者 (白星羽)時間5年前 (2018/11/04 20:04), 編輯推噓1(102)
留言3則, 2人參與, 5年前最新討論串2/2 (看更多)
XML格式的網頁中(網頁網址是http://py4e-data.dr-chuck.net/comments_42.xml), 想爬出裡面count這個tag下面的attribute。 網頁的原始碼大概是長這樣: <comments> <comment> <name>Romina</name> <count>97</count> </comment> <comment> <name>Laurie</name> <count>97</count> </comment> <comment> <name>Bayli</name> <count>90</count> </comment> <comment> <name>Siyona</name> <count>90</count> </comment> <comment> <name>Taisha</name> <count>88</count> </comment> 我寫的部分如下,但抓不到Attribute (顯示為none),可以請教為什麼嗎? import urllib.request, urllib.parse, urllib.error import xml.etree.ElementTree as ET import ssl # Ignore SSL certificate errors ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE url = 'http://py4e-data.dr-chuck.net/comments_42.xml' html = urllib.request.urlopen(url, context=ctx).read().decode('utf-8') tree = ET.fromstring(html) counts = tree.findall('.//count') print('counts:', len(counts)) for item in counts: print('Attribute:', item.get("count")) -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.250.154.48 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1541333072.A.3E8.html

11/04 23:15, 5年前 , 1F
因為它就沒有attribute
11/04 23:15, 1F

11/04 23:17, 5年前 , 2F
你如果要那個數字那是它的text
11/04 23:17, 2F

11/05 08:31, 5年前 , 3F
https://goo.gl/fVm5fd 可以先查一下 直接.text就可以
11/05 08:31, 3F
文章代碼(AID): #1Rtk1GFe (Python)
文章代碼(AID): #1Rtk1GFe (Python)