一份平平无奇的python作业演示
32浏览 • 2小时前 •
科技综合
• MA120469
前几天刷到MA120353,开玩笑问了句能不能把写过的编程作业放出来,结果还真行...那还说啥嘞,不发白不发(
这是22年秋季学期文科计算机基础课的作业,要求使用函数、正则表达式等内容写一份爬虫程序,已经是我对python编程的最高了解了,但在喵站众多科技大佬眼中肯定是贻笑大方的,不要嘲笑我呱
作业要求如下图所示:

我的代码:
import re
import urllib.request
def price(n):
i = n[1:]
j = i.replace(",", "").replace(".00","")
k = float(j)
return k
def get_html(url):
html = urllib.request.urlopen(url).read().decode("utf-8")
return html
def find(html):
patt = re.compile(r'<span class="price">(.*?)</span>')
prices = []
price_list = patt.findall(html)
n = 1
for i in price_list:
if i != "" and i != " ":
p = price(i)
prices.append(p)
print(f"价格{n}:{p:.2f}元")
n = n + 1
return prices
url = "https://www.microsoftstore.com.cn/hardware/xbox-game"
html = get_html(url)
price_list = find(html)
sum = 0
for i in range(len(price_list)):
sum = sum + price_list[i]
print(f"平均价格:{sum/len(price_list):.2f}元")
代码解释:
(几年过去忘得差不多了,这部分重新查了一下简单写写)
- 分别导入正则表达式工具和网络请求工具。
- 编写price函数完成价格转换,把价格中和数字无关的部分都去掉,最后转化为浮点数。
- 编写get_html函数读取网页内容,使用utf-8编码解码。
- 编写find函数解析从网页提取到的价格。通过正则表达式提取价格,创建prices空列表,同时把提取到的价格信息存到price_list里。逐个处理price_list中的价格信息(忽略空价格),调用price函数转为数字后添加到prices列表,并依次输出带编号的价格。
- 上面的函数编写好了,这里把目标网址存到变量url里等待使用。调用get_html函数读取网页内容,再调用find函数提取价格并处理。
- 创建初始值为0的累加变量,循环处理price_list中的每个位置,将价格累加,最后用总价除以价格数,保留两位小数输出平均价格。
输出结果:

(不过打开网页核对的话,会发现最上面那栏的四个价格没提取到,不知道为什么)
未经作者允许,禁止转载
#python
#爬虫
9
10
