练习题的要求是从这个网页http://py4e-data.dr-chuck.net/comments_42.html里提取数字,
并把这些数字转换为float型后求和。
网页截图如下

网页源代码截图:

查看网页源代码发现数值前后的tag是"span",因此用span来定位,用for 循环查看这个tag,
tag.contents[0]表示这个数字,
再用
k = float(tag.contents[0])
把数字转换为float型,累加求和即可。
最后代码如下:
# To run this, you can install BeautifulSoup
# https://pypi.python.org/pypi/beautifulsoup4
# Or download the file
# http://www.py4e.com/code3/bs4.zip
# and unzip it in the same directory as this file
from urllib.request import urlopen
from bs4 import BeautifulSoup
import ssl
# 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()
soup = BeautifulSoup(html, "html.parser")
# Retrieve all of the anchor tags
sum = 0
tags = soup('span')
for tag in tags:
# Look at the parts of a tag
# print('TAG:', tag)
# print('URL:', tag.get('href', None))
# print('Contents:', tag.contents[0])
k = float(tag.contents[0])
# print(k)
sum = sum + k
print('Sum:',sum)
kkkkk这是第一篇代码博客!想不到有朝一日自己可以写这样的内容!!
这是我在Coursera上Python课程的练习题,还处于代码学习初级阶段,在描述上可能漏洞很多,希望会变得更加厉害!
✌️


被折叠的 条评论
为什么被折叠?



