1 server
# selenium web框架示例 @app.route(methods=['POST'], rule='/badiu/login') def login_baidu(): # 获取请求信息 req_json_data = json.loads(request.get_data()) username = req_json_data['username'] password = req_json_data['password'] print(username) print(password) respone_json_data = { 'code': 1, 'data': [], 'msg': '请求成功!' } # selenium 部分 from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait import time from selenium.webdriver.common.keys import Keys browser = webdriver.Firefox() browser.get('http://www.baidu.com/') # 隐式等待 browser.implicitly_wait(30) browser.maximize_window() browser.find_element_by_xpath("//*[@id='kw']").send_keys('测试') browser.find_element_by_xpath("//input[@value='百度一下']").click() # 右上角 登录 按钮 try: login_a_locator = (By.XPATH, "//a[text()='登录']") # 显示等待 login_elemnt = WebDriverWait(browser, 10).until( expected_conditions.visibility_of_element_located(login_a_locator)) login_elemnt.click() except NoSuchElementException as e: print('元素不存在') except Exception as e: print('获取控件发生错误') # 如果出现 扫码登录 ,点击下 用户名登录 按钮 try: login_p_locator = (By.XPATH, "//p[text()='用户名登录']") # 显示等待 login_p_elemnt = WebDriverWait(browser, 10).until( expected_conditions.visibility_of_element_located(login_p_locator)) if (login_p_elemnt is not None): login_p_elemnt.click() browser.find_element_by_xpath("//input[@name='userName']").send_keys(username) browser.find_element_by_xpath("//input[@name='password']").send_keys(password) time.sleep(2) browser.find_element_by_xpath("//input[@id='TANGRAM__PSP_11__submit']").click browser.find_element_by_xpath("//input[@id='TANGRAM__PSP_11__submit']").send_keys(Keys.ENTER) except NoSuchElementException as e: print('元素不存在') except Exception as e: print('获取控件发生错误') # 判断头像是否存在 try: touxiang = browser.find_element_by_xpath("(//span[@class ='s-top-img-wrapper']//img)[1]") if (touxiang is not None): respone_json_data['msg'] = username + ' login success !' return respone_json_data else: respone_json_data['msg'] = username + ' login false !' return respone_json_data except Exception as e: respone_json_data['code'] = 1001 respone_json_data['msg'] = username + ' no user img !' return respone_json_data
2 client
# 请求执行selenium host = 'http://127.0.0.1:9090' path = '/badiu/login' headers = { "Content-Type": "application/json;charset=UTF-8" } params = { 'username': 'lizi_selenium', 'password': '123456' } resp = session.post(url=host+path, headers=headers, json=params) if(resp.status_code == 200): print(resp.json()) else: print(resp.status_code) print(resp.text)