单一的元素定位方法不能满足所有元素的定位,可以根据每个元素的特点来找到合适的方法,可以参考下图的方法:
elementFind.py
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from common.log import log
class ElementFind(object):
def __init__(self, driver):
self.driver = driver
def find_element(self, locator, timeout=2, internal=0.2):
"""
:param locator:
:param timeout:
:param internal:
:return:
"""
for _ in range(2):
log.info('001:step --> find_element:{ele} time={num}'.format(ele=locator, num=_ + 1))
try:
element = WebDriverWait(self.driver, timeout, internal).until(EC.presence_of_element_located(locator))
return element
except Exception as e:
log.warning('[BS]_404:unknown error! %s' % e)
break
用百度页面搜索做例子,输入框和查询框通过id定位如下: