20211215卢泽 2022-2022-2 《Python程序设计》实验四报告
20211215卢泽 2022-2022-2 《Python程序设计》实验四报告
课程:《Python程序设计》
班级: 2112
姓名: 卢泽
学号:20211215
实验教师:王志强
实验日期:2022年5月28日
必修/选修: 公选课
1.实验内容
2. 实验过程及结果
爬虫项目部分
1.购买云服务器
图一 服务器的购买
2.下载putty和winscp,并链接上云服务器
图二 远程链接的截图
3. 配置python3环境
图三 安装并配置python3环境
4.在云服务器上运行
图四 运行程序
图五 运行结果存到了一个txt文件里
图六 爬到的内容
爬虫程序源码:
#!/usr/bin/env python import requests from bs4 import BeautifulSoup titles=[] urls=[] keyword=input("please input the keyword")#输入关键字 pagenum=input("please input page number")#前几页 txt_name="keyword"+keyword+"in"+pagenum+"content.txt" with open(txt_name,'w',encoding='gbk',errors='ignore') as f:#创建文件 f.write(txt_name+'\r') f.close() for i in range(1,int(pagenum)+1):#遍历关键词的页数 html="http://www.ofweek.com/newquery.action?keywords="+keyword+"&type=1&pagenum="+str(i)#根据关键词和页数生成对应的链接 resp=requests.get(html)#建立链接 resp.encoding='gbk'#读取中文时不会出现乱码 content=resp.text bs=BeautifulSoup(content,'html.parser') for news in bs.select('div.zx-tl'):#每个标题都是存在类名为no-pic的li标签里面(可以去看维科网搜索关键词后的网页源代码去发现标题的存在标签。基本上都是存在相同的标签里面。) url=news.select('a')[0]['href']#提取文章出链接 urls.append(url) title=news.select('a')[0].text提取文章标题 titles.append(title) for i in range(len(urls)):#遍历每篇文章的链接 resp=requests.get(urls[i]) resp.encoding='gbk' content=resp.text bs=BeautifulSoup(content,'html.parser') page_content=bs.select('div.artical-content')[0].text#可以发现文章的内容是存在类名为artical-content的div块里面 with open(txt_name,'a',encoding='gbk',errors='ignore') as f:#写入刚刚建立的txt文件 f.write("\n"+titles[i]+page_content) f.close() print("txt file has been recorded")
以上为爬虫项目
项目2:微信自动通知成绩,催体温,天气预报。
主要使用win32api模块win32框架下的都能用,但是微软不给华为云提供Windows服务了,所以没能上机调试(主要是改linux框架下的代码工作量太大,截至交作业的时间我实在是做不完了),但是本机上是能实现的。
以下是代码介绍:
首先是调用的库
import win32clipboard as w#调用剪切板的库 import win32con#窗口切换的库
import win32gui#窗口切换和移动的库 import win32api#操控鼠标键盘的库import time import os import openpyxl#excel操作相关的库 from bs4 import BeautifulSoup#下面这仨不用多介绍吧,爬虫用的 import json import requests
然后是微信自动发消息相关的函数
# 把文字放入剪贴板 def setText(aString): w.OpenClipboard() w.EmptyClipboard() w.SetClipboardData(win32con.CF_UNICODETEXT, aString) w.CloseClipboard() # 模拟ctrl+V def ctrlV(): win32api.keybd_event(17, 0, 0, 0) # ctrl win32api.keybd_event(86, 0, 0, 0) # V win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键 win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0) # 模拟alt+s def altS(): win32api.keybd_event(18, 0, 0, 0) win32api.keybd_event(83, 0, 0, 0) win32api.keybd_event(83, 0, win32con.KEYEVENTF_KEYUP, 0) win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0) # 模拟enter def enter(): win32api.keybd_event(13, 0, 0, 0) win32api.keybd_event(13, 0, win32con.KEYEVENTF_KEYUP, 0) # 模拟单击 def click(): win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) # 移动鼠标的位置 def movePos(x, y): win32api.SetCursorPos((x, y))
爬虫相关函数
def get_content(html, cityname): """处理得到有用信息保存数据文件""" final = [] # 初始化一个列表保存数据 bs = BeautifulSoup(html, "html.parser") # 创建BeautifulSoup对象 body = bs.body data = body.find('div', {'id': '7d'}) # 找到div标签且id = 7d # 下面爬取当天的数据 data2 = body.find_all('div', {'class': 'left-div'}) text = data2[2].find('script').string text = text[text.index('=') + 1:-2] # 移除改var data=将其变为json数据 jd = json.loads(text) dayone = jd['od']['od2'] # 找到当天的数据 final_day = [] # 存放当天的数据 data_all = [] count = 0 for i in dayone: temp = [] if count <= 23: temp.append(i['od21']) # 添加时间 temp.append(cityname + '市') # 添加城市 temp.append(i['od22']) # 添加当前时刻温度 temp.append(i['od24']) # 添加当前时刻风力方向 temp.append(i['od25']) # 添加当前时刻风级 temp.append(i['od26']) # 添加当前时刻降水量 temp.append(i['od27']) # 添加当前时刻相对湿度 temp.append(i['od28']) # 添加当前时刻控制质量 # print(temp) final_day.append(temp) data_all.append(temp) count = count + 1 # 下面爬取24h的数据 ul = data.find('ul') # 找到所有的ul标签 li = ul.find_all('li') # 找到左右的li标签 i = 0 # 控制爬取的天数 for day in li: # 遍历找到的每一个li if i < 7 and i > 0: temp = [] # 临时存放每天的数据 date = day.find('h1').string # 得到日期 date = date[0:date.index('日')] # 取出日期号 temp.append(date) inf = day.find_all('p') # 找出li下面的p标签,提取第一个p标签的值,即天气 temp.append(inf[0].string) tem_low = inf[1].find('i').string # 找到最低气温 if inf[1].find('span') is None: # 天气预报可能没有最高气温 tem_high = None else: tem_high = inf[1].find('span').string # 找到最高气温 temp.append(tem_low[:-1]) if tem_high[-1] == '℃': temp.append(tem_high[:-1]) else: temp.append(tem_high) i = i + 1 return final_day, final def getHTMLtext(url): """请求获得网页内容""" try: r = requests.get(url, timeout=30) r.raise_for_status() r.encoding = r.apparent_encoding print("Success") return r.text except: print("Fail") return " "
主函数
if __name__ == "__main__": # 获取鼠标当前位置 hwnd = win32gui.FindWindow("WeChatMainWndForPC", None) win32gui.ShowWindow(hwnd, win32con.SW_SHOW) win32gui.MoveWindow(hwnd, 0, 0, 1000, 700, True) os.chdir(r"C:\Users\lenovo\Desktop")#把excel的操作路径先设好 workbook = openpyxl.load_workbook('2112.xlsx')#打开我们班的物理成绩表 sheet = workbook.active url1 = 'http://www.weather.com.cn//weather//101010900.shtml' # 24h天气中国天气网 html1 = getHTMLtext(url1) data1, data1_7 = get_content(html1, "北京")#获取北京的天气 maxtemp = data1_7[0][3] mintemp = data1_7[0][2] weather = data1_7[0][1] for i in range(1, sheet.max_row + 1): cell1 = sheet.cell(row=i, column=2)#获取第i行第二列的元素,也就是人名 cell2 = sheet.cell(row=i, column=3)#获取第i行第三列的元素,也就是成绩 time.sleep(0.01) # 1.移动鼠标到通讯录位置,单击打开通讯录 movePos(28, 147) click() # 2.移动鼠标到搜索框,单击,输入要搜索的名字 movePos(148, 35) click() setText(cell1.value) # 好友 ctrlV() time.sleep(1) # 停0.2秒,给微信一个反应的时间 enter() time.sleep(0.3) setText('明天最高温是'+maxtemp) ctrlV() altS() time.sleep(0.3) setText('明天最低温是'+mintemp) ctrlV() altS() time.sleep(0.3) setText('明天天气是'+weather) ctrlV() altS() time.sleep(0.3) setText('报一下体温') ctrlV() altS() time.sleep(0.3) setText('你的物理成绩是'+str(cell2.value)) ctrlV() altS() time.sleep(0.3)
我的excel表格是这样的
整个效果非常好,达到预期目标。
实验感悟与思考
近些天来学python想动手写一个微信自动发消息的程序,然后不断的完善他,一开始用的是itchat模块,然后发现被ban了,然后换思路,改用屏幕操控的思路,最开始只能发一条简单的消息,到后来可以在excel表格里给同学们发个性化的消息,到最后可以再加上爬虫的知识,最后很有成就感。
参考资料
https://blog.csdn.net/qq_35332332/article/details/124160124?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165296377816782425157348%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=165296377816782425157348&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~times_rank-1-124160124-null-null.142^v10^pc_search_result_control_group,157^v4^control&utm_term=python%E7%BE%A4%E5%8F%91%E5%BE%AE%E4%BF%A1%E6%B6%88%E6%81%AF&spm=1018.2226.3001.4187
https://blog.csdn.net/xunkhun/article/details/79266283?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522165399490916781435472737%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=165399490916781435472737&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_positive~default-1-79266283-null-null.142^v11^pc_search_result_control_group,157^v12^control&utm_term=%E7%88%AC%E8%99%AB%E5%A4%A9%E6%B0%94&spm=1018.2226.3001.4187
https://blog.csdn.net/weixin_44288604/article/details/120731317
结课感想与体会
1.在本学期学习过程中,我收获很多,不仅仅学到了python这门编程语言的基础语法,还有socket套接字编程,计算机网络等以后才会接触的内容,开拓了我的眼界,这些内容我觉得非常好,以后的教学里可以保留。
2.对于前面的基础语法部分,我认为老师讲的有点太细了,其实字符串函数可以把他发群里,然后老师布置习题,学生在解决问题的时候,自己就会研究那些函数,课后也可以预留一些习题供同学们去做。
3.对于后面的进阶知识部分,我认为老师讲的有点太快了,很多时候我还不知其所以然老师就过去了,学过计算机导论的同学可能接受的快一点,我个人确实是有点跟不上,课后看了很多资料才勉强理解。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构