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)
你可以選擇span.comments,即:'soup.select('span.comments')'。然後獲取文本,轉向int和sum。 –