Best Python code snippet using selene_python
app_selenium.py
Source: app_selenium.py
1from selenium.webdriver.chrome.options import Options as ChromeOptions2from selenium.webdriver.firefox.options import Options as FirefoxOptions3from selenium.webdriver.ie.options import Options as IeOptions4from selenium import webdriver5from selenium.webdriver.common.action_chains import ActionChains6from selenium.webdriver.support.select import Select7from selenium.webdriver.support.ui import WebDriverWait8from selenium.webdriver.support import expected_conditions as EC9from selenium.webdriver.common.by import By10import getpass11import time12import re13import traceback14driver = '' # รฆยตยรจยงยรฅยยจdriver15driver_dict = {} # รฆยตยรจยงยรฅยยจdriverรฅยญยรฅย
ยธรงยฑยปรฅยยรฏยผยรฆยยนรคยพยฟรฅยยฉรงยยจkeyรฅยฎยรคยฝยรฏยผย16driver_num = 0 # รฅยยจรฆยยkeyรฏยผย17def driver_key_num(driver):18 """19 รฅยยจรฆยยdriverรคยปยฅรฅย
ยจรฅยฑยรฅยญยรฅย
ยธรฅยฝยขรฅยผยรจยพยรฅยยบรฏยผย20 :param driver: driverรฏยผย21 :return:รฅยญยรฅย
ยธรงยยkeyรฏยผย22 """23 global driver_num24 global driver_dict25 driver_num_key = "driver_key" + str(driver_num)26 now_num = driver_num27 driver_num += 128 driver_dict[driver_num_key] = driver29 driver_key = list(driver_dict.keys())30 return driver_key[now_num]31def frame_xpath(browser_name, xpath, frame_flag=False):32 """33 xpathรฅยยรฅยยรฏยผย34 :param browser_name: รฆยตยรจยงยรฅยยจdriverรฏยผย35 :param xpath: รฅยพย
รฅยคยรงยยxpathรฏยผย36 :param frame_flag: รฆยยฏรฅยยฆรฆยยรฅยยรฆยยขframeรฏยผย37 :return: xpath38 """39 try:40 xpath.index(",/โ")41 xpath_list = xpath.split(",")42 for i in range(len(xpath_list)-1):43 browser_name.switch_to.frame(browser_name.find_element_by_xpath(xpath_list[i]))44 frame_flag = True45 return xpath_list[-1], frame_flag46 except ValueError as ve:47 #print(ve)48 return xpath, frame_flag49def frame_handle(browser_name, frame_location, frame_type):50 """51 frameรฅยยรฆยยขรฏยผย52 :param browser_name: รฆยตยรจยงยรฅยยจdriverรฏยผย53 :param frame_location: frameรฅยฎยรคยฝยรฅยยผรฏยผย54 :param frame_type: frameรฅยฎยรคยฝยรงยฑยปรฅยยรฏยผย55 :return:56 """57 if frame_location:58 if frame_type == "frame_str":59 browser_name.switch_to.frame(frame_location)60 else:61 browser_name.switch_to.frame(int(frame_location) - 1)62 return63def driver_handle(browser_name):64 """65 รฅยยรฆยยขรฅยฝยรฅยยรฆยตยรจยงยรฅยยจdriverรฏยผย66 :param browser_name: driverรฅยยรฉยยรฅยยรฏยผย67 :return:driver,68 """69 if browser_name:70 return driver_dict[browser_name]71 else:72 global driver73 return driver74# รจยยรจยยรคยธยรจยฆยรคยธยรจยฆยรฅยยรฆยยรคยธยรคยธยชรฅยยฝรฆยยฐรฏยผย75def browser_chrome(browser_path="", driver_path=""):76 """77 รจยฐยทรฆยญยรฅยย
รฆ ยธรฆยตยรจยงยรฅยยจรฅย
ยผรฅยฎยนรฏยผย78 :param browser_path: รฆยตยรจยงยรฅยยจรจยทยฏรฅยพยรฏยผย79 :param driver_path: รฉยฉยฑรฅยยจรจยทยฏรฅยพยรฏยผย80 :return: driverรฏยผย81 """82 global driver83 if len(browser_path) > 0:84 options = ChromeOptions()85 options.binary_location = browser_path86 else:87 options = None88 if len(driver_path) == 0 :89 driver_path = "chromedriver"90 driver = webdriver.Chrome(executable_path=driver_path, options=options)91 return driver92def browser_ie(browser_path="", driver_path=""):93 """94 ieรฅยย
รฆ ยธรฆยตยรจยงยรฅยยจรฅย
ยผรฅยฎยนรฏยผย95 :param browser_path: รฆยตยรจยงยรฅยยจรจยทยฏรฅยพยรฏยผย96 :param driver_path: รฉยฉยฑรฅยยจรจยทยฏรฅยพยรฏยผย97 :return: driverรฏยผย98 """99 global driver100 if len(browser_path) > 0:101 options = IeOptions()102 options.binary_location = browser_path103 else:104 options = None105 if len(driver_path) == 0 :106 driver_path = "IEDriverServer.exe"107 driver = webdriver.Ie(executable_path=driver_path, options=options) # รฉยยรจยฆยรฅยยจรจยฎยพรงยฝยฎ-รฅยฎยรฅย
ยจ-รฅยยรคยธยชรฅยยบรฅยยรคยธยญรงยปยรคยธยรฅยยฏรงยยจรฅยฎยรฅย
ยจรฆยจยกรฅยผยรฏยผย108 return driver109def browser_firefox(browser_path="", driver_path=""):110 """111 รงยยซรงยยรฅยย
รฆ ยธรฆยตยรจยงยรฅยยจรฅย
ยผรฅยฎยนรฏยผย112 :param browser_path: รฆยตยรจยงยรฅยยจรจยทยฏรฅยพยรฏยผย113 :param driver_path: รฉยฉยฑรฅยยจรจยทยฏรฅยพยรฏยผย114 :return: driverรฏยผย115 """116 global driver117 if len(browser_path) > 0:118 options = FirefoxOptions()119 options.binary_location = browser_path120 else:121 options = None122 if len(driver_path) == 0 :123 driver_path = "geckodriver"124 driver = webdriver.Firefox(executable_path=driver_path, options=options)125 return driver126def open_selenium(url, browser_type="br360", path_selenium="", chrome_driver="", open_type="newDriver"):127 """128 รฆยยรฅยผยรฆยตยรจยงยรฅยยจรฏยผย1129 :param url: รฆยยรฅยผยรงยฝยรงยซยรฅยยฐรฅยยรฏยผย130 :param path_selenium: รฆยตยรจยงยรฅยยจรฅยยฐรฅยยรฏยผย131 :param chrome_driver: รฉยฉยฑรฅยยจรฅยยฐรฅยยรฏยผย132 :param open_type: รฆยยรฅยผยรงยฑยปรฅยยรฏยผย133 :param browser_type: รฆยตยรจยงยรฅยยจรงยฑยปรฅยยรฏยผย134 :return: driverรฏยผย135 """136 browser_select = {137 "br360" : browser_chrome,138 "chrome" : browser_chrome,139 "firefox": browser_firefox,140 "ie": browser_ie141 }142 sys_name = getpass.getuser()143 if len(path_selenium) == 0 and browser_type == "br360":# 360รฉยปยรจยฎยครฅยยฐรฅยยรฏยผยรฆยตยรจยฏยรคยฝยฟรงยยจรฏยผย144 path_selenium = r"C:\Users\%s\AppData\Roaming\360se6\Application\360se.exe" % sys_name # 360รฉยปยรจยฎยครฅยฎยรจยฃย
รคยฝยรงยฝยฎรฏยผย145 if len(chrome_driver) == 0 and browser_type == "br360":146 chrome_driver = r'C:\Users\%s\Desktop\chromedriver.exe' % sys_name147 global driver148 if driver != '':149 if open_type == "newWindow" :150 """151 รฆยยฐรฆ ยรงยญยพรฏยผยรฆยตยรจยงยรฅยยจ รฆยยฐรงยชยรฅยยฃรฆยยรฅยผยรจยฟยรฆยยฅ,seleniumรฆยฒยกรฆยยรฏยผยรฆยยรฆยยถรคยฝยฟรงยยจjsรงยยรฏยผย152 รฅยยรฆยยขรฅยฝยรฅยยรงยชยรฅยยฃรฏยผยรฅยยรฆยฏยรจยพยรฅยคยงรฏยผยรคยพยรจยตยรงยฝยรฉยกยตรฏยผยรฉยยจรฅยยรงยฝยรฉยกยตรฆย รฆยณยรคยฝยฟรงยยจรฆยยรงยคยบwindow.open not functionรฏยผยรฆยยรงยยรฆยยฏรคยพยรจยตยรงยฝยรฉยกยตjsรฏยผยรจยยรฉยยจรฅยยรงยฝยรฉยกยตjsรคยธยรฅย
ยจรฅยฏยผรจยยดรฏยผย153 """154 window_new = 'window.open("' + url + '");'155 driver.execute_script(window_new)156 windows = driver.window_handles157 driver.switch_to.window(windows[-1]) # รฅยยรฆยยขรฅยฝยรฅยยรงยชยรฅยยฃรฏยผย158 driver_key = driver_key_num(driver)159 return driver_key160 elif open_type == "nowWindow" :161 driver.get(url) # รฅยฝยรฅยยรฆ ยรงยญยพรฏยผย162 driver_key = driver_key_num(driver) # driverรคยผยรฆยยรฉยยรฅยคยรฅยยผรฏยผยรคยฝยรฆยยฏรฅยยปรฆยยรงยยรจยฏยรฏยผยrpaรฆย รฆยณยรจยพยรฅยยบรฏยผย163 return driver_key164 else:165 driver = browser_select[browser_type](path_selenium, chrome_driver)166 # รจยฎยพรงยฝยฎรจยฏยทรฆยฑยรจยถย
รฆยยถรฆยยถรฉยยดรฏยผยรฅยพย
รคยผยรฅยยรฏยผย167 driver.set_page_load_timeout(600)168 driver.set_script_timeout(600)169 try:170 driver.get(url)171 except Exception as exc:172 print(exc)173 driver.execute_script("window.stop()")174 finally:175 driver_key = driver_key_num(driver)176 return driver_key177 else:178 driver = browser_select[browser_type](path_selenium, chrome_driver)179 # รจยฎยพรงยฝยฎรจยฏยทรฆยฑยรจยถย
รฆยยถรฆยยถรฉยยดรฏยผยรฅยพย
รคยผยรฅยยรฏยผย180 driver.set_page_load_timeout(600)181 driver.set_script_timeout(600)182 try:183 driver.get(url)184 except Exception as exc:185 print(exc)186 driver.execute_script("window.stop()")187 finally:188 driver_key = driver_key_num(driver)189 return driver_key190def click_selenium(xpath, click_type="left_click", browser_name=None):191 """192 รงยยนรฅยยปรคยบยรคยปยถรฏยผย1193 :param xpath: xpathรฅยยฐรฅยยรฏยผย194 :param click_type: รงยยนรฅยยปรงยฑยปรฅยยรฏยผย195 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย196 :return:197 """198 current_driver = driver_handle(browser_name)199 chain = ActionChains(current_driver)200 xpath, frame_flag = frame_xpath(current_driver, xpath)201 element = current_driver.find_element_by_xpath(xpath)202 click_dict = {203 "left_click" : chain.click,204 "left_double_click" : chain.double_click,205 "click_and_hold": chain.click_and_hold,206 "right_click": chain.context_click207 }208 click_dict[click_type](element).perform()209 windows = current_driver.window_handles210 current_driver.switch_to.window(windows[-1]) # รฅยยรฆยยขรฅยฝยรฅยยรงยชยรฅยยฃรฏยผย211 if frame_flag: # รฉยยรฅยยบframeรฏยผย212 current_driver.switch_to.default_content()213 return214def grab_selenium(xpath, browser_name=None):215 """216 รฆยยรฅยยรฅยยรคยธยชรคยฟยกรฆยยฏรฏยผย217 :param xpath: xpathรฅยยฐรฅยยรฏยผย218 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย219 :return: รฅยยรคยธยชรฆยยรฅยยรฅยยผรฏยผย220 """221 current_driver = driver_handle(browser_name)222 xpath, frame_flag = frame_xpath(current_driver, xpath)223 data_info = current_driver.find_element_by_xpath(xpath).text224 if frame_flag: # รฉยยรฅยยบframeรฏยผย225 current_driver.switch_to.default_content()226 return data_info227def batch_grab_selenium(xpath, browser_name=None):228 """229 รฆยยรฅยยรฆยยนรฉยยรคยฟยกรฆยยฏรฏยผย230 :param xpath: xpathรฅยยฐรฅยยรฏยผย231 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย232 :return: รจยฟยรฅยยรฆยยรฅยยรงยยรฆยยฐรงยปยรฏยผย233 """234 current_driver = driver_handle(browser_name)235 xpath, frame_flag = frame_xpath(current_driver, xpath)236 data_info_batch = current_driver.find_elements_by_xpath(xpath)237 data_infos = []238 for i in data_info_batch:239 data_infos.append(i.text)240 if frame_flag: # รฉยยรฅยยบframeรฏยผย241 current_driver.switch_to.default_content()242 return data_infos243def close_selenium(close_type="allClose", browser_name=None):244 """245 รฅย
ยณรฉยยญรฆยยรฆยยรงยยรฉยยขรฏยผยรฉยยรฅยยบdriverรฏยผย246 รฆยยรจยย
รฅย
ยณรฉยยญรฉยยครงยฌยฌรคยธยรคยธยชรคยปยฅรฅยคยรงยยรฅย
ยถรคยปยรฉยกยตรฉยยขรฏยผย1รงยฌยฌรคยธยรคยธยชรฉยกยตรฉยยขรฅยยฅรฆยยรฏยผย247 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย248 :return:249 """250 current_driver = driver_handle(browser_name)251 if close_type=="un_nowClose" :252 windows = current_driver.window_handles # รฅยยรฆยยขรฅยฝยรฅยยรงยชยรฅยยฃรฏยผย253 window_num = len(windows)254 for i in range(window_num-1): # รฅย
ยณรฉยยญรงยฌยฌรคยธยรคยธยชรคยปยฅรฅยคยรงยยรฉยกยตรฉยยขรฏยผย255 current_driver.switch_to.window(windows[i+1])256 current_driver.close()257 else:258 current_driver.quit()259 return260def close_selenium_page(browser_name=None):261 """262 รฅย
ยณรฉยยญรฅยฝยรฅยยรงยยรฉยยขรฏยผย1263 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย264 :return:265 """266 current_driver = driver_handle(browser_name)267 current_driver.close()268 windows = current_driver.window_handles269 current_driver.switch_to.window(windows[-1]) # รฅยยรฆยยขรฅยฝยรฅยยรงยชยรฅยยฃรฏยผย270 return271def input_selenium(xpath, text, browser_name=None):272 """273 รจยพยรฅย
ยฅรคยฟยกรฆยยฏรฏยผย1274 :param xpath: xpathรฅยยฐรฅยยรฏยผย275 :param text: รจยพยรฅย
ยฅรฅยย
รฅยฎยนรฏยผย276 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย277 :return:278 """279 current_driver = driver_handle(browser_name)280 xpath, frame_flag = frame_xpath(current_driver, xpath)281 current_driver.find_element_by_xpath(xpath).send_keys(text)282 if frame_flag: # รฉยยรฅยยบframeรฏยผย283 current_driver.switch_to.default_content()284 return285def refresh_selenium(browser_name=None):286 """287 รฉยกยตรฉยยขรฅยยทรฆยยฐรฏยผย288 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย289 :return:290 """291 current_driver = driver_handle(browser_name)292 current_driver.refresh()293 return294def back_selenium(browser_name=None):295 """296 รฉยกยตรฉยยขรฅยยรฉยยรฏยผย297 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย298 :return:299 """300 current_driver = driver_handle(browser_name)301 current_driver.back()302 return303def forward_selenium(browser_name=None):304 """305 รฉยกยตรฉยยขรฅยยรจยฟยรฏยผย306 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย307 :return:308 """309 current_driver = driver_handle(browser_name)310 current_driver.forward()311 return312def max_selenium(browser_name=None):313 """314 รฅยฝยรฅยยรงยชยรฅยยฃรฆยยรฅยคยงรฅยยรฏยผย315 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย316 :return:317 """318 current_driver = driver_handle(browser_name)319 current_driver.maximize_window()320 return321def url_selenium(browser_name=None):322 """323 รจยยทรฅยยรฅยฝยรฅยยdriverรฅยฏยนรฅยบยรงยยurlรฏยผย324 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย325 :return: รจยฟยรฅยยรฅยฝยรฅยยurlรฏยผย326 """327 current_driver = driver_handle(browser_name)328 url = current_driver.current_url329 return url330def existence_selenium(xpath, browser_name=None):331 """332 รฅยยครฆยยญรฅย
ยรงยด รฆยยฏรฅยยฆรฅยญยรฅยยจรฏยผย333 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย334 :return: รฆยยฏรฅยยฆรฅยญยรฅยยจรฏยผย335 """336 current_driver = driver_handle(browser_name)337 xpath, frame_flag = frame_xpath(current_driver, xpath)338 flag = True339 try:340 current_driver.find_element_by_xpath(xpath)341 except Exception as exc:342 flag = False343 finally:344 if frame_flag: # รฉยยรฅยยบframeรฏยผย345 current_driver.switch_to.default_content()346 return flag347def attribute_selenium(xpath, attribute_name="", browser_name=None):348 """349 รจยยทรฅยยรฅย
ยรงยด รฅยฑยรฆยยงรฏยผย350 :param xpath: xpathรจยทยฏรฅยพยรฏยผย351 :param attribute_name: รฅยฑยรฆยยงรฅยยรงยงยฐรฏยผย352 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย353 :return: รฅยฑยรฆยยงรฅยยผรฏยผย354 """355 current_driver = driver_handle(browser_name)356 xpath, frame_flag = frame_xpath(current_driver, xpath)357 attribute = current_driver.find_elements_by_xpath(xpath)358 attribute_value = []359 if attribute_name=="" :360 attribute_name="outerHTML"361 # attribute_name = "innerHTML"362 for i in attribute:363 attribute_value.append(i.get_attribute(attribute_name))364 if frame_flag: # รฉยยรฅยยบframeรฏยผย365 current_driver.switch_to.default_content()366 return attribute_value367def select_selenium(xpath, text, match_type="equal_match", browser_name=None):368 """369 รฉยยรฆยยฉรคยธยรฆยยรฆยกยรฏยผย370 :param xpath: xpathรจยทยฏรฅยพยรฏยผย371 :param text: รคยธยรฆยยรฆยกยรฅยยนรฉย
ยรฆยยรฆยยฌรฏยผย372 :param match_type: รฅยยนรฉย
ยรงยฑยปรฅยยรฏยผย373 :param browser_name: รฅยฏยนรฅยบยรฆยตยรจยงยรฅยยจdriverรฏยผย374 :return:375 """376 current_driver = driver_handle(browser_name)377 # frame_handle(current_driver, frame_location, frame_type)378 xpath, frame_flag = frame_xpath(current_driver, xpath)379 selector = Select(current_driver.find_element_by_xpath(xpath))380 like_text = []381 if match_type == "like_match" :382 pattern = ".*" + text + ".*"383 for i in selector.options:384 temp_text = re.findall(pattern, i.text)385 if len(temp_text)>0 :386 like_text.extend(temp_text)387 if len(like_text)>0:388 selector.select_by_visible_text(like_text[0])389 if frame_flag: # รฉยยรฅยยบframeรฏยผย390 current_driver.switch_to.default_content()391 return392 else:393 if frame_flag: # รฉยยรฅยยบframeรฏยผย394 current_driver.switch_to.default_content()395 return396 selector.select_by_visible_text(text)397 if frame_flag: # รฉยยรฅยยบframeรฏยผย398 current_driver.switch_to.default_content()399 return400def selenium_driver_wait(xpath, browser_name=None, wait_second=20):401 """402 รฆยยพรงยคยบรงยญยรฅยพย
รฏยผยรงยญยรฅยพย
รฅย
ยรงยด รฅย รจยฝยฝรฏยผย403 :param xpath: xpathรจยทยฏรฅยพยรฏยผย404 :param wait_second: รฉยปยรจยฎยครจยถย
รฆยยถรฆยยถรฉยยดรฏยผย405 :param browser_name: รฆยตยรจยงยรฅยยจkeyรฏยผย406 :return: รฆยยฏรฅยยฆรฅย รจยฝยฝรฅยฎยรฆยยรฏยผย407 """408 current_driver = driver_handle(browser_name)409 wait_flag = False410 try:411 WebDriverWait(current_driver, int(wait_second), 0.5).until(EC.presence_of_element_located((By.XPATH, xpath)))412 wait_flag = True413 return wait_flag414 except Exception as exc:415 print(exc)416 return wait_flag417def alert_grab_selenium(browser_name=None, time_out=20):418 current_driver = driver_handle(browser_name)419 try:420 WebDriverWait(current_driver, int(time_out), 0.5).until(EC.alert_is_present())421 alert = current_driver.switch_to.alert422 return alert.text423 except Exception as exc:424 #print(exc)425 return426 #current_driver.switch_to.active_element427def alert_click_selenium(browser_name=None, time_out=20, operation_type="confirm"):428 current_driver = driver_handle(browser_name)429 try:430 WebDriverWait(current_driver, int(time_out), 0.5).until(EC.alert_is_present())431 alert = current_driver.switch_to.alert432 if operation_type=="confirm" :433 alert.accept()434 else:435 alert.dismiss()436 return True437 except Exception as exc:438 err_info= traceback.format_exc()439 return err_info440def test_br():441 """442 รฆยตยรจยงยรฅยยจรฆยตยรจยฏยรฏยผย443 :return:444 """445 if not None:446 print(len(""))447 # options = firefox_options()448 # options.binary_location = r"C:\Program Files (x86)\Mozilla Firefox\firefox.exe"449 # driver_firefox = webdriver.Firefox(options=None, executable_path="geckodriver")450 # driver_firefox.get('https:/โ/โwww.baidu.com')451 # ie_path = r'C:\Users\shen\Desktop\IEDriverServer.exe' #รฉยยรจยฆยรฅยยจรจยฎยพรงยฝยฎ-รฅยฎยรฅย
ยจ-รฅยยรคยธยชรฅยยบรฅยยรคยธยญรงยปยรคยธยรฅยยฏรงยยจรฅยฎยรฅย
ยจรฆยจยกรฅยผยรฏยผย452 # driver_ie = webdriver.Ie(executable_path=ie_path)453 # driver_ie.get('https:/โ/โwww.baidu.com')454 chrome_path = r'C:\Users\shen\Desktop\chromedriver_win32 (1)\chromedriver.exe'455 driver_chrome1 = webdriver.Chrome(executable_path=chrome_path)456 driver_chrome1.get('https:/โ/โwww.baidu.com')457 driver_chrome2 = webdriver.Chrome(executable_path=chrome_path)458 driver_chrome2.get('https:/โ/โm.jb51.net/โw3school/โtiy/โt.asp-f=html_select_name.htm')459 input_selenium('/โ/โ*[@id="kw"]', 'python', driver_chrome1)460 # select_selenium('/โhtml/โbody/โselect', 'Au', 'like_match', browser_name=driver_chrome1, frame_location="i")461 # print(attribute_selenium('/โhtml/โbody/โselect', browser_name=driver_chrome1))462 time.sleep(5)463 driver_chrome1.quit()464 # print(driver_chrome2)465def test():466 """467 รฅย
ยถรคยปยรฆยตยรจยฏยรฏยผย468 :return:469 """470 # รฉยยรจยฆยรงยยรฆยยรคยปยถรงยยรจยทยฏรฅยพย471 path = r'./โ'472 # รฆยยรฅยยฐรงยปยรฅยฏยนรจยทยฏรฅยพย473 #return os.path.abspath(path)474 # รจยยทรฅยยรงยณยปรงยปยรงยยจรฆยยทรฅยยรฏยผย475 print(getpass.getuser())476 sys_name = getpass.getuser()477 # C:\Users\shen\AppData\Roaming\360se6\Application\360se.exe478 path_selenium = r"C:\Users\%s\AppData\Roaming\360se6\Application\360se.exe" % sys_name479 print(path_selenium)480 print()481 print(type(driver))482if __name__ == '__main__':483 #test(),รจยตยรฆยบยรฅย รจยฝยฝรคยธยรฅยยฐรงยยรฏยผย iframeรงยยรฏยผยรคยฝยฟรงยยจjsรงยยรฏยผย484 """485 https:/โ/โhao.360.com/โ?wd_xp1486 http:/โ/โrpaii.com/โ#487 https:/โ/โwww.baidu.com/โ488 /โ/โ*[@id="kw"]489 /โ/โ*[@id="su"]490 /โ/โdiv[contains(@class, 'c-container')]/โh3491 /โ/โ*[@id="hotsearch-content-wrapper"]/โli[1]/โa/โspan[2]492 /โ/โli[contains(@class, 'hotsearch-item')]493 file:/โ/โ/โC:/โUsers/โshen/โDesktop/โ1.html494 /โhtml/โbody/โselect495 Audi496 """497 open_selenium("file:/โ/โ/โC:/โUsers/โshen/โDesktop/โalert.html")498 #time.sleep(1)499 #print(selenium_driver_wait('/โ/โ*[@attr_name="attr_value"]', 60))500 #open_selenium("file:/โ/โ/โC:/โUsers/โshen/โDesktop/โ1.html")501 #open_selenium("https:/โ/โm.jb51.net/โw3school/โtiy/โt.asp-f=html_select_name.htm")502 #open_selenium("https:/โ/โwww.w3school.com.cn/โtiy/โt.asp?f=html_select", browser_type="ie", chrome_driver=r'C:\Users\shen\Desktop\IEDriverServer.exe')503 #open_selenium("https:/โ/โwww.baidu.com")504 #input_selenium('/โ/โ*[@id="kw"]', 'python')505 print(grab_selenium("/โhtml/โbody/โdiv"))506 click_selenium('/โhtml/โbody/โbutton[1]')507 time.sleep(1)508 print(alert_grab_selenium())509 #time.sleep(5)510 time.sleep(1)511 alert_click_selenium()512 time.sleep(1)513 print(grab_selenium("/โhtml/โbody/โdiv"))514 click_selenium('/โhtml/โbody/โbutton[2]')515 time.sleep(1)516 print(alert_grab_selenium())517 alert_click_selenium(operation_type="cancle")518 time.sleep(1)519 # alert_click_selenium()520 # time.sleep(1)521 print(grab_selenium("/โhtml/โbody/โdiv"))522 #aa = grab_selenium("/โ/โli[contains(@class, 'hotsearch-item')]")523 #print(grab_selenium("/โhtml/โbody/โdiv"))524 #print(batch_grab_selenium("/โ/โdiv[contains(@class, 'c-container')]/โh3"))525 #print(attribute_selenium('/โhtml/โbody/โselect'))526 #print(attribute_selenium('/โhtml/โbody/โselect',"name"))527 #select_selenium('/โ/โ*[@id="a1"],/โ/โ*[@id="b2"],/โhtml/โbody/โselect','Audi','like_match')528 #print(grab_selenium('/โ/โ*[@id="a1"],/โ/โ*[@id="b2"],/โhtml/โbody/โselect'))529 #time.sleep(5)530 close_selenium("allClose")531 #test_br()532 #print(frame_xpath("/โhtml/โbody/โiframe[1],/โhtml/โbody/โiframe[2],/โhtml/โbody/โiframe,/โhtml/โbody/โselect"))...
linux_browser_driver.py
Source: linux_browser_driver.py
1# Copyright (C) 2016 Igalia S.L. All rights reserved.2#3# Redistribution and use in source and binary forms, with or without4# modification, are permitted provided that the following conditions are5# met:6#7# * Redistributions of source code must retain the above copyright8# notice, this list of conditions and the following disclaimer.9#10# * Redistributions in binary form must reproduce the above11# copyright notice, this list of conditions and the following disclaimer12# in the documentation and/โor other materials provided with the13# distribution.14#15# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS16# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT17# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR18# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT19# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,20# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT21# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,22# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY23# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT24# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE25# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.26import os27import sys28import tempfile29import logging30import subprocess31try:32 import psutil33except ImportError:34 pass35from webkitpy.benchmark_runner.utils import force_remove36from browser_driver import BrowserDriver37_log = logging.getLogger(__name__)38class LinuxBrowserDriver(BrowserDriver):39 browser_name = None40 process_search_list = []41 platform = 'linux'42 def __init__(self):43 self.process_name = self._get_first_executable_path_from_list(self.process_search_list)44 if self.process_name is None:45 raise ValueError('Cant find executable for browser {browser_name}. Searched list: {browser_process_list}'.format(46 browser_name=self.browser_name, browser_process_list=self.process_search_list))47 def prepare_env(self, config):48 self._browser_process = None49 self._browser_arguments = None50 self._temp_profiledir = tempfile.mkdtemp()51 self._test_environ = dict(os.environ)52 self._test_environ['HOME'] = self._temp_profiledir53 def restore_env(self):54 force_remove(self._temp_profiledir)55 def close_browsers(self):56 if self._browser_process:57 if self._browser_process.poll() is None: # still running58 if 'psutil' in sys.modules:59 main_browser_process = psutil.Process(self._browser_process.pid)60 browser_children = main_browser_process.children(recursive=True)61 _log.info('Killing browser {browser_name} with pid {browser_pid} and cmd: {browser_cmd}'.format(62 browser_name=self.browser_name, browser_pid=self._browser_process.pid,63 browser_cmd=' '.join(main_browser_process.cmdline()).strip() or main_browser_process.name()))64 main_browser_process.kill()65 for browser_child in browser_children:66 if browser_child.is_running():67 _log.info('Killing still alive {browser_name} child with pid {browser_pid} and cmd: {browser_cmd}'.format(68 browser_name=self.browser_name, browser_pid=browser_child.pid,69 browser_cmd=' '.join(browser_child.cmdline()).strip() or browser_child.name()))70 browser_child.kill()71 else:72 _log.info('Killing browser {browser_name} with pid {browser_pid}'.format(73 browser_name=self.browser_name, browser_pid=self._browser_process.pid))74 self._browser_process.kill()75 _log.warning('python psutil not found, cant check for '76 'still-alive browser childs to kill.')77 else:78 _log.error('Browser {browser_name} with pid {browser_pid} ended prematurely with return code {browser_retcode}.'.format(79 browser_name=self.browser_name, browser_pid=self._browser_process.pid,80 browser_retcode=self._browser_process.returncode))81 def launch_url(self, url, options, browser_build_path):82 if not self._browser_arguments:83 self._browser_arguments = [url]84 exec_args = [self.process_name] + self._browser_arguments85 _log.info('Executing: {browser_cmdline}'.format(browser_cmdline=' '.join(exec_args)))86 self._browser_process = subprocess.Popen(exec_args, env=self._test_environ,87 stdout=subprocess.PIPE,88 stderr=subprocess.STDOUT)89 def launch_webdriver(self, url, driver):90 try:91 driver.maximize_window()92 except Exception as error:93 _log.error('Failed to maximize {browser} window - Error: {error}'.format(browser=driver.name, error=error))94 _log.info('Launching "%s" with url "%s"' % (driver.name, url))95 driver.get(url)96 def _get_first_executable_path_from_list(self, searchlist):97 searchpath = [os.path.curdir] + os.environ['PATH'].split(os.pathsep)98 for program in searchlist:99 for path in searchpath:100 fullpath = os.path.abspath(os.path.join(path, program))101 if os.path.isfile(fullpath) and os.access(fullpath, os.X_OK):102 return fullpath103 return None104 def _screen_size(self):105 # load_subclasses() from __init__.py will load this file to106 # check the platform defined. Do here a lazy import instead of107 # trying to import the Gtk module on the global scope of this108 # file to avoid ImportError errors on other platforms.109 # Python imports are cached and only run once, so this should be ok.110 import gi111 gi.require_version('Gtk', '3.0')112 gi.require_version('Gdk', '3.0')113 from gi.repository import Gtk, Gdk114 if Gtk.get_major_version() == 3 and Gtk.get_minor_version() < 22:115 screen = Gtk.Window().get_screen()116 return screen.get_monitor_geometry(screen.get_primary_monitor())117 else:118 display = Gdk.Display.get_default()119 monitor = display.get_primary_monitor()...
test_subheader_nav.py
Source: test_subheader_nav.py
1import unittest2import sys3import os4sys.path.append(os.path.join(os.path.dirname(__file__), '..'))5from core import test_core6from utils import env_util, webdriver_util7WEB_SITE = env_util.get_env_url()8START = WEB_SITE+'start-your-business'9START_BEST = WEB_SITE+'7638-best-background-check-services.html'10START_ARTICLE = WEB_SITE+'7623-businesses-for-sale.html'11GROW = WEB_SITE+'grow-your-business'12BUILD = WEB_SITE+'build-your-career'13LEAD = WEB_SITE+'lead-your-team'14FIND = WEB_SITE+'find-a-solution'15ARTICLE = WEB_SITE+'7400-putting-apple-pay-to-work-and-how-you-can-too.html'16 17def verifySubNavigation(self, expected_color, browser_name):18 sub_nav_bar = self.driver.find_element_by_css_selector('.altNav.unit')19# nav_link_bar_part = self.driver.find_element_by_css_selector('.altNavList.line.bg'+str(nav_number))20 self.assertTrue(sub_nav_bar.is_displayed(), 'sub navigation bar is not displayed')21 nav_links = self.driver.find_elements_by_css_selector('.altNavList.line.mqMedOff .subItem>a')22 for link in nav_links:23 self.assertTrue(link.is_displayed(), 'sub nav link is not displayed')24 sub_nav = self.driver.find_element_by_css_selector('.wrap.altNavLiner')25# nav_link_color = nav_link_bar_part.value_of_css_property('background-color')26 sub_nav_color = sub_nav.value_of_css_property('background-color')27 sub_nav_bar_color = sub_nav_bar.value_of_css_property('background-color')28 self.assertEquals(sub_nav_color,sub_nav_bar_color, 'nav bar color and color behind nav links do not match')29 self.assertEqual(sub_nav_color, expected_color, 'color is not correct')30 side_ads_css = '#ctMedia'31 if(webdriver_util.is_element_present(self.driver, side_ads_css)):32 if("chrome" or "headless" in browser_name):33 expected_color = u'rgba(0, 0, 0, 0)'34 else:35 expected_color = u'rgb(0, 0, 0)'36 self.assertEquals(sub_nav_bar_color, expected_color, ' Nav bar is covering background/โside ads')37class SubheaderTestCase(test_core.TestCore):38 def testStartBusinessPage(self):39 self.driver.get(START)40 browser_name = env_util.get_browser()41 if("chrome" or "headless" in browser_name):42 verifySubNavigation(self, u'rgba(0, 83, 186, 1)', browser_name)43 else:44 verifySubNavigation(self, u'rgb(0, 83, 186)', browser_name)45 46 def testStartBusinessBestPick(self):47 self.driver.get(START_BEST)48 browser_name = env_util.get_browser()49 if("chrome" or "headless" in browser_name):50 verifySubNavigation(self, u'rgba(23, 166, 255, 1)', browser_name)51 else:52 verifySubNavigation(self, u'rgb(23, 166, 255)', browser_name)53 54 def testStartBusinessArticle(self):55 self.driver.get(START_ARTICLE)56 browser_name = env_util.get_browser()57 if("chrome" or "headless" in browser_name):58 verifySubNavigation(self, u'rgba(0, 83, 186, 1)', browser_name)59 else:60 verifySubNavigation(self, u'rgb(0, 83, 186)', browser_name)61 62 def testGrowBusiness(self):63 self.driver.get(GROW)64 browser_name = env_util.get_browser()65 if("chrome" or "headless" in browser_name):66 verifySubNavigation(self, u'rgba(205, 0, 93, 1)', browser_name)67 else:68 verifySubNavigation(self, u'rgb(205, 0, 93)', browser_name) 69 70 def testBuildCareer(self):71 self.driver.get(BUILD)72 browser_name = env_util.get_browser()73 if("chrome" or "headless" in browser_name):74 verifySubNavigation(self, u'rgba(0, 205, 183, 1)', browser_name)75 else:76 verifySubNavigation(self, u'rgb(0, 205, 183)', browser_name)77 78 def testLeadTeam(self):79 self.driver.get(LEAD)80 browser_name = env_util.get_browser()81 if("chrome" or "headless" in browser_name):82 verifySubNavigation(self, u'rgba(255, 93, 21, 1)', browser_name)83 else:84 verifySubNavigation(self, u'rgb(255, 93, 21)', browser_name)85 86 def testFindSolution(self):87 self.driver.get(FIND)88 browser_name = env_util.get_browser()89 if("chrome" or "headless" in browser_name):90 verifySubNavigation(self, u'rgba(23, 166, 255, 1)', browser_name)91 else:92 verifySubNavigation(self, u'rgb(23, 166, 255)', browser_name)93 94 def testArticle(self):95 self.driver.get(ARTICLE)96 browser_name = env_util.get_browser()97 if("chrome" or "headless" in browser_name):98 verifySubNavigation(self, u'rgba(205, 0, 93, 1)', browser_name)99 else:100 verifySubNavigation(self, u'rgb(205, 0, 93)', browser_name)101 102if __name__ == "__main__":103 suite = unittest.TestLoader().loadTestsFromTestCase(SubheaderTestCase)...
statistics_handler.py
Source: statistics_handler.py
1#!/โusr/โbin/โpython2.42#3# Copyright 2010 Google Inc. All Rights Reserved.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http:/โ/โwww.apache.org/โlicenses/โLICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16"""Computes average scores for browsers."""17import datetime18from google.appengine.ext import db19from google.appengine.ext import webapp20from google.appengine.ext.webapp.util import run_wsgi_app21from handlers import base22from models import browser_score23COMPUTE_AVERAGE_SCORE_URL = '/โstats/โaverage'24COMPUTE_MULTI_SUITE_AVERAGE_URL = '/โstats/โmulti'25class ComputeAverageScore(webapp.RequestHandler):26 """Handler for computing average suite scores.27 Computes average scores for each browser involved in a suite.28 """29 # Disable 'Invalid method name' lint error.30 # pylint: disable-msg=C640931 def get(self):32 """Calculates the average suite score per test browser."""33 suite_key = self.request.get('suite')34 suite = db.get(db.Key(suite_key))35 test_browsers = suite.GetTestBrowsers()36 # Fetch all the results (page-delta).37 pd_results = []38 query = suite.results39 pd = query.fetch(1000)40 last_cursor = query.cursor()41 while pd:42 pd_results.extend(pd)43 query = query.with_cursor(last_cursor)44 pd = query.fetch(1000)45 last_cursor = query.cursor()46 scores = {}47 counts = {}48 for test_browser in test_browsers:49 scores[test_browser.key().name()] = 050 counts[test_browser.key().name()] = 051 for result in pd_results:52 # Check for invalid results53 if result.score < 0:54 continue55 browser_key = result.GetTestBrowser().key().name()56 # Only count results that are non-ignored.57 if not result.ignore:58 scores[browser_key] += result.score59 counts[browser_key] += 160 for test_browser in test_browsers:61 test_browser_key = test_browser.key().name()62 scores[test_browser_key] /โ= float(counts[test_browser_key])63 average_score = browser_score.GetOrInsertBrowserScore(suite, test_browser)64 average_score.layout_score = scores[test_browser_key]65 average_score.num_urls = counts[test_browser_key]66 average_score.date = datetime.datetime.utcnow()67 average_score.put()68 self.redirect('/โsuite/โstats?suite=%s' % suite_key)69class GetAverageScoreOfMultiSuites(base.BaseHandler):70 """Handler for computing average score among multiple suites.71 Computes the average scores for each browser in the specified suites.72 """73 # Disable 'Invalid method name' lint error.74 # pylint: disable-msg=C640975 def get(self):76 """Calculates the average score per test browser across mutliple suites."""77 suite_keys = self.request.get_all('suite')78 browser_scores = {}79 browser_num_urls = {}80 for suite_key in suite_keys:81 suite = db.get(db.Key(suite_key))82 for test_browser in suite.GetTestBrowsers():83 score = browser_score.GetOrInsertBrowserScore(suite, test_browser)84 browser_name = unicode(test_browser)85 if not browser_name in browser_scores:86 browser_scores[browser_name] = 087 browser_num_urls[browser_name] = 088 total_urls = browser_num_urls[browser_name] + score.num_urls89 browser_scores[browser_name] = (90 browser_scores[browser_name] * browser_num_urls[browser_name] +91 score.layout_score * score.num_urls) /โ float(total_urls)92 browser_num_urls[browser_name] = total_urls93 score_output = []94 num_urls_output = []95 keys = browser_scores.keys()96 keys.sort()97 for browser_name in keys:98 score_output.append('["%s", %f]' % (browser_name,99 browser_scores[browser_name]))100 num_urls_output.append('%s (%d urls)' % (browser_name,101 browser_num_urls[browser_name]))102 template_values = {'browser_scores': ',\n'.join(score_output),103 'test_browsers': num_urls_output}104 self.RenderTemplate('suite_stats.html', template_values)105application = webapp.WSGIApplication(106 [(COMPUTE_AVERAGE_SCORE_URL, ComputeAverageScore),107 (COMPUTE_MULTI_SUITE_AVERAGE_URL, GetAverageScoreOfMultiSuites)],108 debug=True)109def main():110 run_wsgi_app(application)111if __name__ == '__main__':...
Check out the latest blogs from LambdaTest on this topic:
There are times when developers get stuck with a problem that has to do with version changes. Trying to run the code or test without upgrading the package can result in unexpected errors.
Automating testing is a crucial step in the development pipeline of a software product. In an agile development environment, where there is continuous development, deployment, and maintenance of software products, automation testing ensures that the end software products delivered are error-free.
Web applications continue to evolve at an unbelievable pace, and the architecture surrounding web apps get more complicated all of the time. With the growth in complexity of the web application and the development process, web application testing also needs to keep pace with the ever-changing demands.
โTest frequently and early.โ If youโve been following my testing agenda, youโre probably sick of hearing me repeat that. However, it is making sense that if your tests detect an issue soon after it occurs, it will be easier to resolve. This is one of the guiding concepts that makes continuous integration such an effective method. Iโve encountered several teams who have a lot of automated tests but donโt use them as part of a continuous integration approach. There are frequently various reasons why the team believes these tests cannot be used with continuous integration. Perhaps the tests take too long to run, or they are not dependable enough to provide correct results on their own, necessitating human interpretation.
Hey LambdaTesters! Weโve got something special for you this week. ????
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!