代码运行视频: https://www.bilibili.com/video/BV1kL4y1i7fg?share_source=copy_web&vd_source=15464a7707b5e62cbcb0cba64276966c
import json
import time
from selenium import webdriver # 导入selenium包
from selenium.webdriver.common.by import By
def testLikes():
# QQ登陆
driver = webdriver.Chrome(r'D:\Drivers\webdriver\chromedriver_win32\chromedriver.exe')
driver.get('http://www.zhihu.com') # 进入官网
driver.maximize_window() # 最大化窗口
driver.find_element(By.XPATH, "//*[@class='Login-socialButtonGroup']/button[2]").click() # QQ登陆
windows_1 = driver.window_handles
driver.switch_to.window(windows_1[1]) # 转换到QQ登陆的窗口
driver.switch_to.frame('ptlogin_iframe') # 进入框架
driver.find_element(By.ID, 'img_out_1693562789').click() # 点击头像登陆
time.sleep(3) # 等待
driver.switch_to.window(driver.window_handles[0]) # 转换到知乎窗口
time.sleep(3)
# 点赞
total_time = 0
for i in range(10):
print("第" + str(i+1) + "次测试点赞功能:")
time_start = time.perf_counter() # 记录开始时间
button = driver.find_element(By.XPATH, "//*[@id='TopstoryContent']/div/div/div/div[1]/div/div/div[2]/div[2]/div/span/button[1]") # 点赞
time_end = time.perf_counter() # 记录结束时间
num1 = button.get_attribute("aria-label") # 获取点赞前的button的属性,记录是否点赞
button.click() # 点赞
# time_end = time.perf_counter() # 记录结束时间
time.sleep(1) # 等待,不然获取的button属性值不变
num2 = button.get_attribute("aria-label") # 获取点赞后的button属性
if num1[0] != num2[0]: # 点赞前后属性变化
print(" 点赞成功!", end='')
else:
print("搜索失败...")
use_time = time_end-time_start # 花费的时间
total_time += use_time
print("花费时间:"+str(use_time))
driver.refresh() # 刷新页面
print("---------")
print("平均花费时间:"+str(total_time/10))
def testWriteArticle():
# QQ登陆
from selenium.webdriver import ChromeOptions
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation']) # 给webdriver的options增加参数
driver = webdriver.Chrome(options=option) # 使用开发者模式运行绕开反爬虫
driver.get('http://www.zhihu.com') # 进入官网
driver.maximize_window() # 最大化窗口
driver.find_element(By.XPATH, "//*[@class='Login-socialButtonGroup']/button[2]").click() # QQ登陆
windows_1 = driver.window_handles
driver.switch_to.window(windows_1[1]) # 转换到QQ登陆的窗口
driver.switch_to.frame('ptlogin_iframe') # 进入框架
driver.find_element(By.ID, 'img_out_1693562789').click() # 点击头像登陆
time.sleep(3) # 等待
driver.switch_to.window(driver.window_handles[0]) # 转换到知乎窗口
time.sleep(3)
# 写文章
total_time = 0
title = ['CS188 project1 Q1 MiniMax', 'CS188 project1 Q2 α β剪枝', 'CS188 project1 Q3 Expectimax', 'CS188 project1 Q4 betterEvaluationFunction', 'CS188 项目4 Q4 消除因子', 'CS188 项目4 Q5 归一化', 'CS188 项目 Q6 变量消除', 'Games101 项目3 rasterize_triangle', 'Games101 项目3 布林冯模型', 'Games101 项目3 凹凸贴图']
content1 = '第一个函数getAction并不需要去修改它,是一个获取下一步行动的函数。而行动则是根据一定分数来评估,这个分数需要调用函数evaluationFunction来获取。最初的evaluationFunction只有基础的功能,需要自己来编写评估函数,返回一个分数。这个分数的设计方式就是计算当前位置与所有食物的曼哈顿距离,取反,和所有鬼魂的距离向乘,加上获取的分数.\n同时如果下一步能够吃到食物或者鬼魂正处于恐惧状态,则可以获得额外的加分。\n编写Minimax智能代理,需要在getAction中编写新的函数,从注释可以获取一些函数的作用。根据提示信息编写函数,在min中会有多个ghost分支需要全部求min。'
content2 = '剪枝只需要在minimax基础上对max、min函数中的不必要搜索的路径剪去,其他部分几乎一样。\n运行python pacman.py -p AlphaBetaAgent -a depth=3 -l smallClassic发现得分比之前会高很多,每走一步所需要的时间花费更少了。'
content3 = 'Expectimax要求不能所有的幽灵都采取min,而是需要根据幽灵的行动方式来采取期望,因此在minimax的基础上修改min函数, 加和所有行动值,然后返回平均值即可. \n可以看到αβ剪枝总是输,而Expectimax大约能赢一半。当吃豆人陷入困境,在Expectimax中他至少会尝试脱困或者自杀,这样就能减少分数惩罚。'
content4 = 'betterEvaluationFunction要求编写一个更好的评估值函数。这次使用了鬼魂的启发值、食物的启发值和恐惧胶囊的启发值来作为返回参数。\n首先幽灵的启发值就是所有幽灵的距离,距离较远则有较高的启发值。食物的启发值则是获取最近的食物,距离近则启发值高。胶囊则是使用个数作为启发值,个数越多启发值越高。'
content5 = '所需做的有,首先,找到消除变量后的所有非条件概率组合。\n先构建新的概率,将需要消去的非条件概率消去,conditionedVariables和variableDomainsDict就是原factor的。\n然后所有的概率组合就是提示中的getAllPossibleAssignmentDicts()函数,使用for循环遍历即可。\n 第二,将相同的行进行加和,设置概率。\n 对于每一个条件组合,每去掉一个变量,都要加和一次概率。设置就的概率组合和新的一样,然后对于每一个消去的变量,分别加到复制的概率之上,这样就是前后相同的行在消去变量之前的概率组合,获取概率然后加和即可。'
content6 = '输入的是一个因子,他所有概率的和不为1,如果所有概率和是0的话,应该返回Nana,否则需要缩放概率来使概率和为1。\n在注释代码部分有说明,新的条件变量包含输入的条件变量还有输入的非条件变量中只有一个domain的。而且我们需要构建一个新的factor,而不是修改输入的factor。新的factor的条件变量包含有输入的factor的条件变量同时还有输入factor中只有一个取值条目的非条件变量。\n首先需要构建新的因子,遍历输入factor的条件变量和无条件变量,新的条件变量是原输入的条件变量和非条件变量中域中只有一个条目的,非条件变量就是剩下的。\n 然后缩放概率,这部分就很简单了,先加和原先的概率,如果输入的概率和为0,返回Nana,不为0则缩放,因为需要缩放后的概率和为1,所以缩放后的概率=1*原概率/概率和。\n注意不能直接遍历variableDomainsDict中的所有变量,因为variableDomainsDict中不仅仅是有条件和无条件变量,还有其他的变量,这个其他的变量导致输出结果错误。'
content7 = '实现函数inferenceByVariableElimination,输入的有四个变量,一个贝叶斯网络bayesNet,一个无条件变量表queryVariables,一个推理条件字典evidenceDict,还有一个消除变量的顺序eliminationOrder。要求使用消除顺序eliminationOrder来迭代消除变量,直到剩下条件变量和查询的变量,同时需要输出因子的所有概率总和为1。最后返回的是P(queryVariables | evidenceDict)。代码中的提示给出了需要使用的函数的作用与功能:getAllCPTsWithEvidence()返回所有条件概率表,joinFactorsByVariable()连接包含变量的所有因子,然后就是之前写的几个函数。并且提示,当待消去的因子只有一个非条件变量的时候,不应该去消去它,而应该直接舍弃。\n所以需要首先遍历消除变量的顺序列表eliminationOrder,分出要消去变量的因子,然后判断这个要消去的因子的无条件变量是否大于1,如果不是的话直接舍弃,是的话则调用之前写的消除因子的函数eliminate消除变量后加到因子表中。当所有待消除的变量都被消除后,就使用之前写的joinFactors函数计算联合概率,最后用归一化函数将所有概率和变为1.'
content8 = '需要实现法向量、颜色、纹理颜色的插值。实现方式和之前的作业2类似,但是设定的数值不再是常数而是按照重心坐标对法向量、颜色、纹理颜色与底纹颜色 (Shading Colors) 进行插值。需要做的是使用插值得到的结果设置 fragment shader payload,并调用 fragment shader 得到计算结果。\n 所以,首先和上次作业一样,找到三角形的边界,然后遍历其中所有像素点,当像素在像素点内,并且这个像素离相机更近,更改像素颜色,更新深度缓冲区。但是其中需要自动插入四个属性,然后获取颜色也不能直接去get,应该使用提示中给出的代码。并且这一次的isinside函数是已经写好的,不用自己去编写。'
content9 = '需要做的就是对于代码中的每个光源,计算环境光、漫反射光和镜面反射光,然后将计算结果加到result_color中。\n首先回顾三种光源的计算公式,公式中,其中kd,ks,ka是三个系数,I是光照强度.\n对于环境光ambient来说,直接用公式ka*I即可,ka已经给出,I就是定义的这个位置的光照强度amb_light_intensity[0],三个光源在这个位置的大小都是同样的大小,所以不用纠结使用顺序问题.\n对于漫反射光,公式为:kd(I/r^2)max(0,n*l) ,kd,I直接使用amb_light_intensity[1],r^2即光源位置light.position到反射点point距离差的平方,因为是向量,所以得使用dot函数来计算点积。而法向量n已给出,归一化成单位向量即可,L就是光源位置light.position到反射点point差的单位向量,当前位置看光源的向量,光源与当前位置的差,然后归一化为单位向量。\n 对于高光,公式为ks(I/r^2)max(0,n*h)^p . \n p已经给出为150,h为观察位置与当前位置夹角的中线的向量,两个向量相加后归一化成单位向量即可.'
content10 = '实现凹凸贴图。注释很详细地给出了需要做的事。\n 大多数代码可以根据提示一步一步将代码写完。\n 有一点就是在计算用相对高度信息,查询那个凹凸贴图图谱的结果的时候,直接使用提示中的代码会报错,题目所给的dU = kh * kn * (h(u+1/w,v)-h(u,v))和dV = kh * kn * (h(u,v+1/h)-h(u,v)),uv是横纵坐标,wh是纹理的宽高,直接用代码计算会报错. \n 原因就是关于坐标取值范围需要规范,对于大于1的坐标需要改变du和dv的计算方式。'
content_list = [content1, content2, content3, content4, content5, content6, content7, content8, content9, content10]
for i in range(10):
driver.find_element(By.XPATH, "//*[@id='root']/div/main/div/div/div[2]/div/div/div/div[1]/div/div[2]/div[1]/div/button[3]").click() # 点发文章
windows1 = driver.window_handles
driver.switch_to.window(windows1[1]) # 转到发文章
time_start = time.perf_counter() # 记录开始时间
# 填写标题
driver.find_element(By.XPATH, "//*[@id='root']/div/main/div/div[2]/div[2]/label/textarea").send_keys(title[i])
# 填写内容
time.sleep(1)
# driver.refresh()
driver.find_element(By.XPATH, '//*[@role="main"]//div[@class="DraftEditor-editorContainer"]//span').send_keys(content_list[i])
time.sleep(1) # 不然太快会找不到元素
driver.find_element(By.XPATH, '//*[@id="root"]/div/main/div/div[1]/div/div[1]/div[1]/div[2]/div[3]/button').click()
time.sleep(1)
driver.find_element(By.XPATH, '//*[@id="root"]/div/main/div/div[1]/div/div[1]/div[1]/div[2]/div[3]/div/div/div[4]/button').click()
time_end = time.perf_counter() # 记录结束时间
use_time = time_end - time_start # 花费的时间
total_time += use_time # 加到总时间
time.sleep(3)
driver.refresh() # 刷新页面去除广告
button = driver.find_element(By.XPATH, '//*[@id="root"]/div/main/div/article/div[4]/div[1]/div/span/button') # 获取自己文章的赞同信息
like_button = button.get_attribute("aria-label")
if like_button[0] == '赞':
print("写文章成功!")
print("花费时间:" + str(use_time))
driver.refresh() # 刷新页面
else:
print("写文章失败...")
driver.close() # 关闭当前窗口
driver.switch_to.window(windows1[0]) # 切回到主窗口
time.sleep(10) # 多睡会儿,否则会被知乎警告发表文章太快了
driver.refresh() # 刷新一下
print("---------")
print("平均花费时间:" + str(total_time / 10))
def testSearch():
# cookies登陆
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
chrome_options.add_argument("--disable-blink-features")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(r'D:\Drivers\webdriver\chromedriver_win32\chromedriver.exe', options=chrome_options)
driver.get('http://www.zhihu.com')
driver.maximize_window()
time.sleep(3)
driver.delete_all_cookies()
with open('cookies.txt', 'r') as f:
cookies_list = json.load(f) # 读取cookies
for cookie in cookies_list:
if isinstance(cookie.get('expiry'), float):
cookie['expiry'] = int(cookie['expiry'])
driver.add_cookie(cookie) # 加入cookies
driver.refresh()
# driver.find_element(By.ID, "Popover1-toggle").send_keys("玫瑰\n")
# 搜索
total_time = 0
searchContent = ['吃饭\n', '睡觉\n', '星星\n', '月亮\n', '太阳\n', '玫瑰\n', '软件测试\n', '手机\n', '笔记本\n', '测试\n']
for i in range(10):
print("第" + str(i + 1) + "次测试搜索功能:")
time_start = time.perf_counter() # 记录开始时间
driver.find_element(By.ID, "Popover1-toggle").send_keys(searchContent[i]) # 搜索框中搜索内容并回车
time_end = time.perf_counter() # 记录结束时间
time.sleep(1) # 等待响应
# button = driver.find_element(By.XPATH, "//*[@id='SearchMain']/div/div/div/div/div[1]/div/div/div/div[2]/span[1]/button[1]")
# button_str = ''
# button_str = button.get_attribute("aria-label") # 获取搜索内容的信息
# if button_str != '': # 如果获取到则搜索成功
# print("搜索成功!")
# else:
# print("搜索失败...")
js1 = "document.documentElement.scrollTop=10000"
driver.execute_script(js1) # 搜索成功的条件 出现滚动条并可操作
print(" 搜索成功!", end='')
use_time = time_end-time_start
total_time += use_time
print("花费时间:" + str(use_time))
driver.back() # 返回主页
print("---------")
print("平均花费时间:" + str(total_time / 10))
def testCollection():
# cookies登陆
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
chrome_options.add_argument("--disable-blink-features")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(r'D:\Drivers\webdriver\chromedriver_win32\chromedriver.exe', options=chrome_options)
driver.get('http://www.zhihu.com')
driver.maximize_window()
time.sleep(3)
driver.delete_all_cookies()
with open('cookies.txt', 'r') as f:
cookies_list = json.load(f)
for cookie in cookies_list:
if isinstance(cookie.get('expiry'), float):
cookie['expiry'] = int(cookie['expiry'])
driver.add_cookie(cookie)
driver.refresh()
# 收藏
total_time = 0
for i in range(10):
print("第" + str(i + 1) + "次测试收藏功能:")
time_start = time.perf_counter() # 记录开始时间
driver.find_element(By.XPATH, '//*[@id="TopstoryContent"]/div/div/div/div[1]/div/div/div[2]/div[2]/div/button[2]').click() # 点击收藏
time.sleep(1)
button = driver.find_element(By.XPATH, '/html/body/div[4]/div/div/div/div[2]/div/div[2]/div/div[1]/div[1]/button') # 收藏按钮
button_class = button.get_attribute("class") # 获取属性class
button.click() # 点击
time_end = time.perf_counter() # 记录结束时间
time.sleep(1)
button_class_after = button.get_attribute("class") # 获取收藏后的class
if button_class_after != button_class: # 前后class变化
print(' 收藏成功!', end='')
use_time = time_end - time_start
total_time += use_time
print("花费时间:" + str(use_time))
driver.refresh()
print("---------")
print("平均花费时间:" + str(total_time / 10))
def testBrowse():
# cookies登陆
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("excludeSwitches", ['enable-automation'])
chrome_options.add_argument("--disable-blink-features")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
driver = webdriver.Chrome(r'D:\Drivers\webdriver\chromedriver_win32\chromedriver.exe', options=chrome_options)
driver.get('http://www.zhihu.com')
driver.maximize_window()
time.sleep(3)
driver.delete_all_cookies()
with open('cookies.txt', 'r') as f:
cookies_list = json.load(f)
for cookie in cookies_list:
if isinstance(cookie.get('expiry'), float):
cookie['expiry'] = int(cookie['expiry'])
driver.add_cookie(cookie)
driver.refresh()
# 浏览
total_time = 0
driver.find_element(By.XPATH, '//*[@id="root"]/div/main/div/div[3]/div[1]/div/div[1]/nav/a[3]').click()
time.sleep(1)
for i in range(10):
print("第" + str(i + 1) + "次测试浏览功能:")
time_start = time.perf_counter() # 记录开始时间
driver.find_element(By.XPATH, '//*[@id="TopstoryContent"]/div/div/div[2]/section['+str(i+1)+']/div[2]/a').click()
windows1 = driver.window_handles
driver.switch_to.window(windows1[1]) # 转到浏览的文章的页面
js1 = "document.documentElement.scrollTop=10000"
driver.execute_script(js1) # 滚动条
time_end = time.perf_counter() # 记录结束时间
time.sleep(0.1)
print(" 浏览成功!", end='')
use_time = time_end - time_start
total_time += use_time
print("花费时间:" + str(use_time))
driver.back() # 返回主页
driver.close() # 关闭
driver.switch_to.window(windows1[0])
print("---------")
print("平均花费时间:" + str(total_time / 10))
if __name__ == '__main__':
# 测试点赞
print("正在测试点赞功能...")
testLikes()
# 测试搜索
print("正在测试搜索功能...")
testSearch()
# 测试收藏
print("正在测试收藏功能...")
testCollection()
# 测试写文章
print("正在测试写文章功能...")
testWriteArticle()
# 测试浏览
print("正在测试浏览功能...")
testBrowse()
from selenium import webdriver
import time
import json
driver = webdriver.Chrome()
# 打开目标网站
driver.get('https://www.zhihu.com')
time.sleep(40) # 留够时间来手动登录
with open('cookies.txt', 'w') as f:
# 将cookies保存为json格式在cookies.txt中
f.write(json.dumps(driver.get_cookies()))
driver.close()