当前位置:   article > 正文

python-Selenium自动化测试笔记(1)——驱动模块封装_selenium关键字驱动的封装

selenium关键字驱动的封装

将Selenium的主要操作封装成class,方便后续调用。

  1. import os, time, faker, random
  2. from typing import Tuple, Union, Dict
  3. from selenium.webdriver import Chrome
  4. from selenium.webdriver.common.by import By
  5. from selenium.webdriver.support.wait import WebDriverWait
  6. from selenium.webdriver.support import expected_conditions as when, expected_conditions
  7. from selenium.webdriver import ActionChains, Keys
  8. class Page:
  9. def __init__(self, driver: Chrome):
  10. self.driver = driver
  11. def goto(self, url):
  12. """ 去哪个url地址 """
  13. # if url.find("https://") != -1:
  14. # return self.browser.get(url)
  15. return self.driver.get(url)
  16. def input(self, locator, values):
  17. """ 输入框当中输入内容 """
  18. el = self.driver.find_element(*locator)
  19. el.send_keys(values)
  20. def clear(self, element):
  21. """ 清空输入框中的内容 """
  22. el = self.driver.find_element(*element)
  23. el.clear()
  24. def click(self, locator):
  25. """ 点击 """
  26. # 设置显性等待时间
  27. wait = WebDriverWait(self.driver, timeout=8)
  28. # 等待某个元素出现并可点击
  29. condition = when.element_to_be_clickable(locator)
  30. # 定位元素.点击按钮
  31. element = wait.until(condition)
  32. # 点击元素
  33. ActionChains(self.driver).click(element).perform()
  34. def double_click(self, locator):
  35. """ 双击 """
  36. # 设置显性等待时间
  37. wait = WebDriverWait(self.driver, timeout=10)
  38. # 等待某个元素出现并可点击
  39. condition = when.element_to_be_clickable(locator)
  40. # 定位元素.点击按钮
  41. element = wait.until(condition)
  42. # 双击元素
  43. ActionChains(self.driver).double_click(element).perform()
  44. def drag_and_drop(self, locator1, locator2):
  45. """ 拖动 """
  46. # 设置显性等待时间
  47. wait = WebDriverWait(self.driver, timeout=10)
  48. condition = when.element_to_be_clickable(locator1)
  49. element1 = wait.until(condition)
  50. # 定位到元素1,定位到元素2
  51. condition = when.element_to_be_clickable(locator2)
  52. element2 = wait.until(condition)
  53. # 拖动元素
  54. ActionChains(self.driver).drag_and_drop(element1, element2).perform()
  55. def is_element_exist(self, element: Tuple[str, Union[str, Dict]], wait_seconds: int = 10) -> bool:
  56. """ 判断元素是否存在 """
  57. by = element[0]
  58. value = element[1]
  59. try:
  60. if by == "id":
  61. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.ID, value)))
  62. elif by == "name":
  63. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.NAME, value)))
  64. elif by == "class":
  65. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.CLASS_NAME, value)))
  66. elif by == "text":
  67. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.LINK_TEXT, value)))
  68. elif by == "partial_text":
  69. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.PARTIAL_LINK_TEXT, value)))
  70. elif by == "xpath":
  71. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.XPATH, value)))
  72. elif by == "css":
  73. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, value)))
  74. elif by == "tag":
  75. WebDriverWait(self.driver, wait_seconds, 1).until(expected_conditions.presence_of_element_located((By.TAG_NAME, value)))
  76. else:
  77. raise NameError("Please enter the correct targeting elements,'id','name','class','text','xpath','css'.")
  78. except:
  79. return False
  80. return True
  81. def get_element_text(self, locator):
  82. """ 元素定位,获取text文本 """
  83. el = self.driver.find_element(*locator)
  84. return el.text
  85. def is_text_exist(self, text: str, wait_seconds: int = 10) -> bool:
  86. """ 判断text是否于当前页面存在 """
  87. for i in range(wait_seconds):
  88. if text in self.driver.page_source:
  89. return True
  90. time.sleep(1)
  91. return False
  92. def is_loaded(self, url, timeout=8):
  93. """ 判断某个 url 是否被加载 """
  94. return WebDriverWait(self.driver, timeout).until(when.url_contains(url))
  95. def get_element_attribute(self, locator, expected):
  96. """ 获取某个元素的属性 """
  97. el = self.driver.find_element(*locator)
  98. return el.get_attribute(expected)
  99. def get_toast_text(self):
  100. """ toast弹窗/获取toast文本内容 """
  101. toast = self.driver.find_element("xpath", "//android.widget.Toast")
  102. return toast.text
  103. def emter(self):
  104. """ 回车 """
  105. return ActionChains(self.driver).send_keys(Keys.ENTER).perform()
  106. def copy(self):
  107. """ 复制快捷键 """
  108. actions = ActionChains(self.driver)
  109. return actions.key_down(Keys.CONTROL).send_keys("c").key_up(Keys.CONTROL).perform()
  110. def paste(self):
  111. """ 粘贴的快捷键 """
  112. actions = ActionChains(self.driver)
  113. return actions.key_down(Keys.CONTROL).send_keys("v").key_up(Keys.CONTROL).perform()
  114. def set_attribute(self, locator, name, value):
  115. """ 设置元素属性(12306) """
  116. el = self.driver.find_element(*locator)
  117. js = f'arguments[0].{name} = f"{value}"'
  118. self.driver.execute_script(js,el)
  119. def switch_to_iframe(self, locator, timeout=10):
  120. """ 切换iframe """
  121. # iframe = self.browser.find_element(*locator)
  122. # self.browser.switch_to.frame(iframe)
  123. # 使用显性等待 切换 iframe
  124. wait = WebDriverWait(self.driver, timeout)
  125. wait.until(when.frame_to_be_available_and_switch_to_it(locator))
  126. def switch_to_default(self):
  127. """ iframe 切回主页面 """
  128. self.driver.switch_to.default_content()
  129. def scroll_to_bottom(self):
  130. """ 滚动到页面底部,使用js操作 """
  131. js = "window.scrollTo(0,document.body.scrollHeight)"
  132. self.driver.execute_script(js)
  133. def screenshot(self, name):
  134. """ 截图(注释的部分,根据个人需求可增or减) """
  135. # day = time.strftime('%Y-%m-%d', time.localtime(time.time()))
  136. # fp = "..\\Result\\" + day
  137. fp = ".\\images\\" # ".":表示上级; "..":表示上上级
  138. tm = time.strftime('%Y-%m-%d-%H_%M', time.localtime(time.time()))
  139. if os.path.exists(fp):
  140. filename = fp + "\\" + tm + '_' + name + '.png'
  141. else:
  142. os.makedirs(fp)
  143. filename = fp + "\\" + tm + '_' + name + '.png'
  144. self.driver.save_screenshot(filename)
  145. def randmon_phone(self):
  146. """ 随机生成一个手机号,或者其他想生成的数据 """
  147. while True:
  148. phone = "130"
  149. for i in range(8):
  150. num = random.randint(0, 9)
  151. phone += str(num)
  152. return phone
  153. def generate_phone_number(self):
  154. """ 随机生成手机号(与上面的实现方法一致,写法用了列表推导式) """
  155. prefix = "130"
  156. suffix = [random.randint(0, 9) for _ in range(8)]
  157. return f"{prefix}{''.join([str(i) for i in suffix])}"
  158. def new_mobile(self):
  159. """ 随机生成手机号,需下载:pip install pytest_facker """
  160. fk = faker.Faker(locale=["zh_CN"])
  161. return fk.phone_number()
  162. if __name__ == '__main__':
  163. pass

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

闽ICP备14008679号