作者starlichin (白星羽)
看板Python
標題Re: [問題] 初學網路爬蟲問題
時間Sun Nov 4 20:04:27 2018
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
→ InfinityGate: 因為它就沒有attribute 11/04 23:15
→ InfinityGate: 你如果要那個數字那是它的text 11/04 23:17