2017-08-30 81 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 ,在循环之外,你只打印计算出的最后一个值,从循环中逃脱)

相关问题