各种元素定位练习:
1、下拉框(不是select)
因为当前想要选择的下拉框内容,可能需滚动才能显示,进而才能点击,这里利用js,将想要定位到的下拉框元素,滚动到页面可见的范围
tar = self.driver.find_element_by_xpath(path) self.driver.execute_script("arguments[0].scrollIntoView();", tar) time.sleep(1) tar.click()
2、封装页面元素查询功能,判断元素是否存在,且是可见的
1 def check_element(self, path, name, tar, time_out=5): 2 try: 3 if path == "xpath": 4 if tar: 5 element1 = WebDriverWait(self.driver, time_out, 1).until( 6 lambda x: x.find_element_by_xpath("//*[contains(text(),'" + name + "')]")) 7 if not element1.is_displayed(): 8 return 0 9 else: 10 return element1 11 else: 12 element1 = WebDriverWait(self.driver, time_out, 1).until(lambda x: x.find_element_by_xpath(name)) 13 if not element1.is_displayed(): 14 return 0 15 else: 16 return element1 17 if path == "css": 18 if tar: 19 ele = '[type="text"][placeholder="{name}"]'.format(name=name) 20 element1 = WebDriverWait(self.driver, time_out, 1).until( 21 lambda x: x.find_element_by_css_selector(ele)) 22 if not element1.is_displayed(): 23 return 0 24 else: 25 return element1 26 27 if not tar: 28 element1 = WebDriverWait(self.driver, time_out, 1).until( 29 lambda x: x.find_element_by_css_selector(name)) 30 if not element1.is_displayed(): 31 return 0 32 else: 33 return element1 34 35 except Exception as e: 36 # 定位失败时,将图片保存,重命名为调用方法名_时间戳.png 37 self.driver.get_screenshot_as_file( 38 error_picture_path +'\' + sys._getframe(1).f_code.co_name + '_' + time.strftime('%Y%m%d%H%M%S', time.localtime( 39 time.time())) + ".png") 40 return 0
3、有时在查找元素的时候,又多个属性一致的元素,有时在用find_element_ 查找元素时,返回的元素并不是想要定位的元素,这个时候除了优化定位路径,还有一种方法就是
利用find_elements去查找元素。不过这种方式,对于同一页面,同时展示属性一致的元素而言是不是很适用的,还是要通过优化定位路径去进行精准定位,才能达到你想要的效果
def check_elements(self, path, element_name, tar=True): if path == "xpath": if tar: element_ = "//*[contains(text(),'" + element_name + "')]" Element = self.driver.find_elements_by_xpath(element_) else: Element = self.driver.find_elements_by_xpath(element_name) for el in Element: if el.is_displayed(): return el break if path == "css": if tar: ele = '[type="text"][placeholder="{name}"]'.format(name=element_name) Element = self.driver.find_elements_by_css_selector(ele) else: Element = self.driver.find_element_by_css_selector(element_name) for el in Element: if el.is_displayed(): return el break
--后续会继续补充