当前位置:   article > 正文

pom学习笔记:kimi的自动化操作

pom学习笔记:kimi的自动化操作

1.先看结构:

声明:我是初学,可能有不合理的地方。

2.Base层。

我是把原来一个kimi的自动问答的代码改过来。

分析:其实我是新手,因为我用的浏览器是固定的,也没有打算和别人用。所以浏览器层面年的全部写死。

其他功能用到什么添什么。一步步完善。

后期我想这个这基层一直用下去。所以会一步步完善的。

base_page.py的内容如下:

  1. import time
  2. from selenium import webdriver
  3. from selenium.webdriver.edge.options import Options
  4. from selenium.webdriver.support.ui import WebDriverWait
  5. from selenium.webdriver.support import expected_conditions as EC
  6. from selenium.webdriver.common.by import By
  7. import pyperclip
  8. import os
  9. class BasePage:
  10. def __init__(self):
  11. edge_user_data_dir = r"C:\Users\Administrator\AppData\Local\Microsoft\Edge\User Data\Default"
  12. edge_options = Options()
  13. edge_options.use_chromium = True
  14. edge_options.add_argument('--disable-extensions') # 禁用浏览器扩展
  15. edge_options.add_argument('--disable-gpu') # 禁用GPU硬件加速
  16. # edge_options.add_argument('--headless') # 禁用GPU硬件加速
  17. edge_options.add_argument(f"--user-data-dir={edge_user_data_dir}")
  18. self.driver = webdriver.Edge(options=edge_options)
  19. self.driver.maximize_window()
  20. self.wait = WebDriverWait(self.driver, 300)
  21. # self.driver = driver
  22. # self.driver.implicitly_wait(10)
  23. def keep_browser_open(self):
  24. """保持浏览器窗口打开,等待用户操作."""
  25. input("按回车键退出程序并关闭浏览器...")
  26. def js_condition(self,driver):
  27. """自定义等待条件函数,检查JavaScript返回值"""
  28. return driver.execute_script("return document.readyState") == "complete"
  29. def open_url(self,url):
  30. self.driver.get(url)
  31. self.wait.until(self.js_condition)
  32. print("页面加载完成")
  33. return True
  34. def find_element(self, loc):
  35. try:
  36. return self.wait.until(EC.element_to_be_clickable(loc))
  37. except Exception as e:
  38. print(f"元素未找到:{loc}")
  39. return False
  40. def find_elements(self, loc):
  41. elements = self.wait.until(EC.presence_of_all_elements_located(loc))
  42. if not elements: # 可选:检查是否找到元素,如果没有,打印提示信息
  43. print(f"没有找到匹配的元素:{loc}")
  44. return elements
  45. def click_element(self,loc):
  46. element = self.find_element(loc)
  47. element.click()
  48. # self.driver.execute_script("arguments[0].click();", element)
  49. def set_text(self,loc,text):
  50. element=self.find_element(loc)
  51. element.send_keys(text)
  52. def full_path(self,filename):
  53. current_dir = os.getcwd()
  54. # 确保文件名加上.txt扩展名
  55. if not filename.endswith('.txt'):
  56. filename += ".txt"
  57. full_path = os.path.join(current_dir, filename)
  58. return full_path
  59. def clipboard_content_to_file(self,filename):
  60. full_path = self.full_path(filename)
  61. clipboard_text = pyperclip.paste()
  62. with open(full_path, 'w', encoding='utf-8') as file:
  63. file.write(clipboard_text)
  64. print(f"剪贴板内容已成功写入到文件: {filename}")
  65. def read_line_from_file(self,filename):
  66. full_path = self.full_path(filename)
  67. numeric_line = None # 初始化为None,表示尚未找到符合条件的行
  68. try:
  69. with open(full_path, 'r', encoding='utf-8') as file:
  70. for line in file:
  71. # 检查行是否以数字开头
  72. if line.strip().startswith(tuple('0123456789')):
  73. numeric_line = line.rstrip('\n') # 找到第一行后移除行尾的换行符并赋值
  74. break # 终止循环
  75. except FileNotFoundError:
  76. print(f"文件 {filename} 未找到。")
  77. except Exception as e:
  78. print(f"读取文件时发生错误: {e}")
  79. print("读取当前行:",numeric_line)
  80. return numeric_line
  81. def del_line_from_file(self, filename):
  82. full_path = self.full_path(filename)
  83. numeric_line = None # 初始化为None,表示尚未找到符合条件的行
  84. lines_to_write_back = [] # 用于存储除了被删除行外的所有行
  85. try:
  86. with open(full_path, 'r', encoding='utf-8') as file:
  87. found = False # 标记是否已找到并处理符合条件的行
  88. for line in file:
  89. if not found and line.strip().startswith(tuple('0123456789')):
  90. numeric_line = line.rstrip('\n') # 找到第一行后移除行尾的换行符并赋值
  91. found = True # 设置标志,表示已找到并处理了符合条件的行
  92. else:
  93. lines_to_write_back.append(line) # 其他行保留,准备写回文件
  94. if found: # 只有在确实找到并处理了符合条件的行后才重写文件
  95. with open(full_path, 'w', encoding='utf-8') as file:
  96. file.writelines(lines_to_write_back)
  97. except FileNotFoundError:
  98. print(f"文件 {filename} 未找到。")
  99. except Exception as e:
  100. print(f"读取或修改文件时发生错误: {e}")
  101. print("删除当前行:", numeric_line)
  102. return numeric_line
  103. def append_content_to_file(self,filename, content):
  104. full_path = self.full_path(filename)
  105. try:
  106. with open(full_path, 'a', encoding='utf-8') as file:
  107. file.write(content + '\n') # 内容后添加换行符,以便于区分多条内容
  108. print(f"内容已成功追加到文件: {filename}")
  109. except Exception as e:
  110. print(f"写入文件时发生错误: {e}")

测试用的代码,都通过了。

  1. url = "https://kimi.moonshot.cn/"
  2. case= BasePage()
  3. case.open_url(url)
  4. #lowImage___hU90c
  5. # img_loc="By.CLASS_NAME", 'login____RTRY'
  6. # img_loc=By.CLASS_NAME, 'lowImage___hU90c'
  7. #
  8. # if case.click_element(img_loc):
  9. # print("ok")
  10. edit_loc= By.XPATH,'//div[@data-slate-node="element"]'
  11. text="你好吗?"
  12. case.send_text(edit_loc,text)
  13. send_loc=By.ID, "send-button"
  14. case.click_element(send_loc)
  15. case.keep_browser_open()

3.page层

分析:因为我计划用于kimi或讯飞或其他,所以在规划时。计划用主域名当成关键字。而每一部分不再分成独立模块,如登录,主页,等。如何有跳转的话,后期根据情况写在base层。

  1. import time
  2. from class_learn.base.base_page import BasePage
  3. from selenium.webdriver.common.by import By
  4. import pyperclip
  5. import os
  6. class KimiPage(BasePage):
  7. def __init__(self):
  8. super().__init__() # 假设BasePage也有初始化driver的逻辑,则需要调用super().__init__()
  9. def web_ready(self,url,ok_loc,nok_loc):
  10. if self.open_url(url):
  11. if self.find_element(ok_loc):
  12. print("发现头像,登录成功")
  13. else:
  14. self.click_element(nok_loc)
  15. def new_page(self,new_loc):
  16. self.click_element(new_loc)
  17. time.sleep(2)
  18. def get_questions(self, op_loc, op_loc1, edit_loc, keywords, send_loc, copy_loc):
  19. self.click_element(op_loc)
  20. time.sleep(1)
  21. self.click_element(op_loc1)
  22. time.sleep(1)
  23. self.set_text(edit_loc, keywords)
  24. self.click_element(send_loc)
  25. time.sleep(2)
  26. self.click_element(copy_loc)
  27. def set_text_and_send(self,edit_loc,text,send_loc):
  28. self.click_element(edit_loc)
  29. time.sleep(1)
  30. self.set_text(edit_loc,text)
  31. self.click_element(send_loc)
  32. def click_copy_and_save(self,copy_loc):
  33. pass
  34. case = KimiPage()
  35. url = "https://kimi.moonshot.cn/"
  36. nok_loc=By.CLASS_NAME, 'login____RTRY' #未登录
  37. ok_loc=By.CLASS_NAME, 'lowImage___hU90c' #已登录
  38. case.web_ready(url,ok_loc,nok_loc)
  39. new_loc=By.XPATH,"//div[@data-testid='msh-sidebar-new']"
  40. case.new_page(new_loc)
  41. op_loc=By.CSS_SELECTOR,".icon___zTPKp svg"
  42. op_loc1=By.CSS_SELECTOR,".itemContainer___eYZxh .content___EPfWU"
  43. op_loc2=By.CSS_SELECTOR,"div:nth-child(2) > .itemContainer___eYZxh .content___EPfWU"
  44. edit_loc=By.XPATH,'//div[@data-slate-node="element"]'
  45. keywords="泌尿系统"
  46. send_loc=By.ID, "send-button"
  47. copy_loc=By.XPATH, "//span[contains(.,'复制')]"
  48. # case.get_questions(op_loc,op_loc1,edit_loc,keywords,send_loc,copy_loc)
  49. # case.clipboard_content_to_file(keywords)
  50. file=keywords+"_ques"
  51. for i in range(100):
  52. if i%10==0:
  53. case.new_page(new_loc)
  54. time.sleep(2)
  55. ask=case.read_line_from_file(keywords)
  56. case.get_questions(op_loc,op_loc2,edit_loc,ask,send_loc,copy_loc)
  57. case.del_line_from_file(keywords)
  58. case.append_content_to_file(file, f"第{i}章 {ask}")
  59. case.append_content_to_file(file,pyperclip.paste())
  60. case.keep_browser_open()

基本完成了,可以自动生成100个问题,自动回答,自动追加到文本中,自动删除已经回答过的问题。方便系统错误后,接着进行,每10个问题自动开始一个新的页面。

感觉比原来好用多了。清晰了,看来代码要不停的写才可以。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/一键难忘520/article/detail/739519
推荐阅读
相关标签
  

闽ICP备14008679号