用python把C#操作OA的例子重写了一下
#手工chrome.exe --remote-debugging-port=9222 --user-data-dir="C:\selenum\AutomationProfile" from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.chrome.options import Options from selenium.webdriver.support import expected_conditions as EC import time chrome_options = Options() chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222") chrome_driver = "chromedriver.exe" driver = webdriver.Chrome(chrome_driver, chrome_options=chrome_options) script = ''' Object.defineProperty(navigator, 'webdriver', { get: () => undefined }) ''' driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script}) wait = WebDriverWait(driver, 10) #超时时长为10s '''driver.get("http://192.168.132.80/login/Login.jsp") # 等待 登录框 出现 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#loginid'))).send_keys("admin") # 等待 密码框 出现 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#userpassword'))).send_keys("1234") # 提交 wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#login'))).click() wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#_ButtonCancel_0'))).click() ''' driver.get("http://192.168.132.80/wui/main.jsp?templateId=3") wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#_ButtonCancel_0'))).click() mainFrame = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#mainFrame'))) driver.switch_to.frame(mainFrame) try: wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, '#more_1560'))).click() except: print("err") # 使用第一种方法切换浏览器【切换到第二个窗口】 windows = driver.window_handles driver.switch_to.window(windows[-1]) time.sleep(1) anchors = driver.find_elements_by_xpath("//a[contains(@href, 'javaScript:openFullWindowHaveBarForWFList')]") #print(type(anchors),len(anchors)) for index in range(len(anchors)) : driver.find_element_by_xpath("//a[contains(@href, 'javaScript:openFullWindowHaveBarForWFList')]").click() #【切换到第三个窗口】 driver.switch_to.window(driver.window_handles[-1]) driver.find_element_by_xpath("//button[contains(@class,'btn_submit')]").click() time.sleep(3) # 【切换到第二个窗口】 driver.switch_to.window(driver.window_handles[-1]) driver.close() driver.quit()
这里循环中处理时没用到循环变量 ,因为切换窗口时页面会自动刷新,所以只需确定总项数,然后每次处理第一项即可。与之前写的C#程序似乎不同。
补充:今天测试失败,将倒数第5行的 time.sleep由1秒改为3秒,成功。