2017-08-30 43 views
0

輸入URL http://py4e-data.dr-chuck.net/comments_42.html(Python 3的操作系統Win7的)列表不顯示預期的輸出

當我運行這段代碼,預期的輸出是包含數字,是標籤這是內部列表在程序中被解析。但我所得到的是列表中的最後一個數字。

請更正程序,以顯示在所有標籤目前號碼的列表被解析

from urllib.request import urlopen 
from bs4 import BeautifulSoup 
import ssl 
import re 

# Ignore SSL certificate errors 
ctx = ssl.create_default_context() 
ctx.check_hostname = False 
ctx.verify_mode = ssl.CERT_NONE 

url = input('Enter - ') 
html = urlopen(url, context=ctx).read() 

# html.parser is the HTML parser included in the standard Python 3 library. 
# information on other HTML parsers is here: 
# http://www.crummy.com/software/BeautifulSoup/bs4/doc/#installing-a-parser 
soup = BeautifulSoup(html, "html.parser") 

# Retrieve all of the anchor tags 
sum_of_num = 0 
tags = soup('tr') 
for tag in tags: 
    # Look at the parts of a tag 
    print('TAG:', tag) 
    num = re.findall('[0-9]+',str(tag)) 
print(num) 
+0

你可以選擇span.comments,即:'soup.select('span.comments')'。然後獲取文本,轉向int和sum。 –

回答

0

如果你想有一個列表,你必須建立一個列表。您需要首先聲明一個空列表,然後在每次迭代中追加值:

res = [] 
for tag in tags: 
    # Look at the parts of a tag 
    print('TAG:', tag) 
    res.append(re.findall('[0-9]+',str(tag))) 

print(res) 

,如果你需要一個非常可讀的輸出,你可以使用pprint

import pprint 
pprint.pprint(res) 

(通過在打印結束num ,在循環之外,你只打印計算出的最後一個值,從循環中逃脫)