webdriver封装
如果框架写的不稳定,在定位或者元素操作时抛错就会停止运行,这里将对webdriver操作加上异常并记录日志
代码
新建base.py 显示等待方法
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from public.log import Log
def element_wait(css, secs=8):
"""
Waiting for an element to display.
"""
by = css[0].strip() #css参数为元素,如css = ("css selector", "a[class='btn btn-primary']")
messages = 'Element: {0} not found in {1} seconds.'.format(css, secs)
if by == "id":
WebDriverWait(driver, secs, 0.5).until(EC.presence_of_element_located(css), messages)
elif by == "name":
WebDriverWait(driver, secs, 0.5).until(EC.presence_of_element_located(css), messages)
elif by == "class name":
WebDriverWait(driver, secs, 0.5).until(EC.presence_of_element_located(css), messages)
elif by == "link text":
WebDriverWait(driver, secs, 0.5).until(EC.presence_of_element_located(css), messages)
elif by == "xpath":
WebDriverWait(driver, secs, 0.5).until(EC.presence_of_element_located(css), messages)
elif by == "css selector":
WebDriverWait(driver, secs, 0.5).until(EC.presence_of_element_located(css), messages)
else:
raise NameError("Please enter the correct targeting elements,'id','name','class','link_text','xpath','css'.")
定位方法选择
def get_element(css):
"""
Judge element positioning way, and returns the element.
"""
by = css[0].strip()
value = css[1].strip()
if by == "id":
element = driver.find_element(by,value)
elif by == "name":
element = driver.find_element(by,value)
elif by == "class name":
element = driver.find_element(by,value)
elif by == "link text":
element = driver.find_element(by,value)
elif by == "xpath":
element = driver.find_element(by,value)
elif by == "css selector":
element = driver.find_element(by,value)
else:
raise NameError("Please enter the correct targeting elements,'id','name','class', 'link_text', 'xpath', 'css'.")
return element
输入框清空和输入
def clear_type(css, text):
"""
Clear and input element.
"""
t1 = time.time()
css1 = css[0] + "->" + css[1]
try:
element_wait(css)
el = get_element(css)
el.clear()
el.send_keys(text)
my_print("{0} Clear and type element: <{1}> content: {2}, Spend {3} seconds".format(success,
css1, text, time.time() - t1))
except Exception:
my_print("{0} Unable to clear and type element: <{1}> content: {2}, Spend {3} seconds".format(fail, css1, text, time.time() - t1))
raise
详见github: https://github.com/zhangmoumou1/selenium_python
版权声明:如无特殊说明,文章均为本站原创,转载请注明出处
本文链接:http://zhangyanc.club/subject/article/selenium-base/
许可协议:署名-非商业性使用 4.0 国际许可协议