Beispiel #1
0
 def accept_alert(self):
     Alert(self.driver).accept()
Beispiel #2
0
 def __init__(self, driver):
     self.driver = driver
     self.wait = WebDriverWait(self.driver, 15)
     self.actions = ActionChains(self.driver)
     self.alerts = Alert(self.driver)
def dialog_alert():
    js_expression = "alert('这是alert提示框')"
    driver.execute_script(js_expression)

    time.sleep(2)
    Alert(driver).dismiss()
Beispiel #4
0
 def get_alert(cls):
     alert = Alert(webd)
     return alert
Beispiel #5
0
 def switch_to_alert(self):
     """Switches focus to an alert on the page.
     Usage:
         driver.switch_to_alert()
     """
     return Alert(self)
Beispiel #6
0
    def extract_json(self, _json):
        command = _json["command"]
        target = _json["target"]
        targets = _json["targets"]
        value = _json["value"]
        execlogger = logging.getLogger('UiTester.exec')

        if "//" in command:
            return "pass"

        elif command == "open":
            if "http" in target:
                self.DRIVE.get(target)
            else:
                self.DRIVE.get(self.URL + target)

        elif command == "setWindowSize":
            target = target.split("x")
            self.DRIVE.set_window_size(target[0], target[1])

        elif "Confirmation" in command:
            if "VisibleConfirmation" in command:
                WebDriverWait(self.DRIVE, 10).until(EC.alert_is_present(),
                                                    self.DRIVE)
                alter = Alert(self.DRIVE)
                alter.accept()

        elif command == "selectFrame":
            target = target.split("=")[-1]

            if target == "parent":
                self.DRIVE.switch_to.default_content()
                return True
            else:
                try:
                    target = int(target)
                except:
                    return traceback.format_exc()
                execlogger.debug(target)
                WebDriverWait(self.DRIVE, 10).until(
                    EC.frame_to_be_available_and_switch_to_it(target),
                    self.DRIVE)

        elif command == "verifyElementPresent":
            target = target.split("path=")[-1]
            print(target)
            try:
                WebDriverWait(self.DRIVE, 10).until(
                    EC.presence_of_element_located((By.XPATH, target)))
                # WebDriverWait(self.DRIVE,10 ,0.1).until(
                #     EC.presence_of_element_located((By.XPATH, target)))
                return self.DRIVE.find_element_by_xpath(target)
            except:
                return traceback.format_exc()

        elif command == "pause":
            time.sleep(int(value))

        elif command == "close":
            try:
                return self.DRIVE.close()
            except:
                return traceback.format_exc()

        elif command == "executeScript":
            try:
                if "open" in value:
                    self.DRIVE.execute_script(value)
                    return WebDriverWait(self.DRIVE,
                                         10).until(EC.new_window_is_opened)
                else:
                    return self.DRIVE.execute_script(value)
            except:
                return traceback.format_exc()

        # elif command == "executeSwich":
        #     print("qqqqqqq")
        #     print(self.DRIVE.window_handles)
        #     try:
        #         self.main_window = self.DRIVE.current_window_handle()
        #         self.DRIVE.execute_script(
        #             "window.open('http://www.twitter.com', 'new window')")
        #         window_after = self.DRIVE.window_handles[1]
        #         self.DRIVE.switch_to.window(window_after)
        #         time.sleep(10)
        #         self.DRIVE.get("https://www.google.com")
        #         self.DRIVE.switch_to.window(window_after)
        #     except:
        #         return traceback.format_exc()

        elif command == "swichWindow":
            try:
                self.main_window = self.DRIVE.current_window_handle
                self.DRIVE.get
                self.DRIVE.switch_to.window(
                    self.DRIVE.window_handles[int(value)])
                # time.sleep(5)
                WebDriverWait(self.DRIVE, 10).until(EC.url_changes(target))
                # while(True):
                #     try:
                #         if self.main_window == self.DRIVE.current_window_handle:
                #             time.sleep(0.1)
                #         else:
                #             break
                #     except:
                #         return traceback.format_exc()
                return self.DRIVE.set_window_position(700, 100)
            except:
                return traceback.format_exc()

        elif command == "returnWindow":
            try:
                self.DRIVE.switch_to.window(self.main_window)
                return self.DRIVE.set_window_position(0, 0)
            except:
                return traceback.format_exc()

        else:
            if targets:
                target_ = self.extract_targets(targets)
                target = None
                for i in target_:
                    try:
                        WebDriverWait(self.DRIVE, 10).until(
                            EC.presence_of_element_located((By.XPATH, i)))
                        target = i
                        break
                    except:
                        return traceback.print_exc()
            else:
                target = target[6:]
                execlogger.debug(target)
                WebDriverWait(self.DRIVE, 10).until(
                    EC.presence_of_element_located((By.XPATH, target)))

            if command == "click":
                WebDriverWait(self.DRIVE, 10).until(
                    EC.element_to_be_clickable((By.XPATH, target)))
                # print(target)
                execlogger.debug(target)
                self.DRIVE.find_elements_by_xpath(target)[0].click()

            elif command == "type" or command == "sendKeys":
                if "${KEY" == value[0:5]:
                    value = getattr(Keys, value[6:-1])

                self.DRIVE.find_elements_by_xpath(target)[0].send_keys(value)
        return True
Beispiel #7
0
 def alert_accept(self):  #确认警告
     Alert(self.driver).accept()
Beispiel #8
0
 def login_False(self):
     alert = Alert(UseBrowser.driver)
     t = alert.text
     alert.accept()
     return t
Beispiel #9
0
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
from selenium.webdriver.common.keys import Keys
import time 

driver = webdriver.Chrome()

driver.get('http://39.107.96.138:3000/signin')
# 删除帖子
driver.implicitly_wait(20)
driver.find_element_by_id('name').send_keys('user1')
driver.find_element_by_id('pass').send_keys('123456')
driver.find_element_by_css_selector('div>input[type="submit"]').click()
driver.maximize_window()
driver.find_element_by_css_selector('a[class="topic_title"]').click()
driver.find_element_by_css_selector('i[class="fa fa-lg fa-trash"]').click()
driver.switch_to_alert
print('text=',Alert(driver).text)
Alert(driver).accept()
driver.back()
driver.refresh()
time.sleep(3)
driver.quit()
Beispiel #10
0
def run_tests(firefox_path=None):
    basedir = os.path.dirname(__file__)
    driver = None
    profile = FirefoxProfile()
    if firefox_path:
        if sys.platform == "darwin" and os.path.isdir(firefox_path):
            firefox_path = os.path.join(firefox_path, "Contents", "MacOS",
                                        "firefox")
        binary = FirefoxBinary(firefox_path)
    else:
        binary = None

    try:
        build1 = tempfile.NamedTemporaryFile(mode="wb",
                                             suffix=".xpi",
                                             delete=False)
        build2 = tempfile.NamedTemporaryFile(mode="wb",
                                             suffix=".xpi",
                                             delete=False)
        try:
            createBuild(basedir, type="gecko", outFile=build1)
            createBuild(os.path.join(basedir, "testhelper"),
                        type="gecko",
                        outFile=build2)
            profile.add_extension(build1.name)
            profile.add_extension(build2.name)
        finally:
            os.unlink(build1.name)
            os.unlink(build2.name)

        driver = WebDriver(profile, firefox_binary=binary)
        driver.wait_until = lambda method: WebDriverWait(
            driver, default_timeout).until(lambda d: method())
        driver.accept_alert = Alert(driver).accept
        driver.keys = Keys

        def chain(*actions):
            for action in actions:
                c = ActionChains(driver)
                action(c)
                c.perform()

        driver.chain = chain

        max_timestamp = {"value": 0}

        def get_urls():
            result = []
            prefix = "[testhelper] Loading: "
            new_timestamp = max_timestamp["value"]
            for item in driver.get_log("browser"):
                timestamp = item["timestamp"]
                if timestamp <= max_timestamp["value"] or not item[
                        "message"].startswith(prefix):
                    continue
                if timestamp > new_timestamp:
                    new_timestamp = timestamp
                result.append(item["message"][len(prefix):])
            max_timestamp["value"] = new_timestamp
            return result

        driver.get_urls = get_urls

        def close_background_tabs():
            driver.execute_script('''
        var event = document.createEvent("Events");
        event.initEvent("testhelper_closeBackgroundTabs", true, false);
        document.dispatchEvent(event);
      ''')

        driver.close_background_tabs = close_background_tabs

        def middle_click(self):
            driver.execute_script(
                '''
        var event = document.createEvent("Events");
        event.initEvent("testhelper_middleclick", true, false);
        arguments[0].dispatchEvent(event);
      ''', self)

        WebElement.middle_click = middle_click

        environment = {
            "__builtins__": __builtins__,
            "driver": driver,
        }

        testdir = os.path.join(basedir, "tests")
        for filename in os.listdir(testdir):
            if filename.startswith(".") or not filename.endswith(".py"):
                continue
            filepath = os.path.join(testdir, filename)
            environment["__file__"] = filepath
            with open(filepath, "rb") as handle:
                exec handle in environment
    finally:
        if driver:
            driver.quit()
        shutil.rmtree(profile.path, ignore_errors=True)
def abeek_login(id, pwd): # abeek login
    if id in driver_hash :
        driver_hash[id].close()
        driver_hash[id].quit()
        del driver_hash[id]  

    options = Options()
    options.add_argument("--headless")
    options.add_argument("--no-sandbox")
    options.add_argument("--disable-dev-shm-usage")
    options.add_argument("--disable-gpu")
    prefs  = {"profile.managed_default_content_settings.images": 2,"profile.default_content_settings.images": 2}
    options.add_experimental_option("prefs", prefs)
    driver = webdriver.Chrome(executable_path="/usr/local/bin/chromedriver", chrome_options=options)
    try:
        driver.get('http://abeek.knu.ac.kr/Keess/comm/support/login/loginForm.action')
    except Exception as e:
        print(e)

    try:
        idForm = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID,'usr_id')))
    except Exception as e:
        print(e)
    idForm.send_keys(id)

    WebDriverWait(driver, 5).until(lambda browser: idForm.get_attribute('value') == id)

    try:
        pwdForm = WebDriverWait(driver, 5).until(EC.presence_of_element_located((By.ID, 'passwd')))
    except Exception as e:
        print(e)
    pwdForm.send_keys(pwd)
    WebDriverWait(driver, 5).until(lambda browser: pwdForm.get_attribute('value') == pwd)
    
    try:
        pwdForm.send_keys(Keys.RETURN)
        try:
            WebDriverWait(driver, 1).until(EC.alert_is_present(),
                                        'Timed out waiting for PA creation ' +
                                        'confirmation popup to appear.')
            print(Alert(driver).text)
            if("PASSWORD 변경일이 3개월이 지났습니다." in Alert(driver).text ) :
                return False, PASSWORD_CHANGE_DATE_THREE_MONTHS

            Alert(driver).accept()
            
            driver.close()
            driver.quit()
            return False, ID_PASSWARD_INCORRECT
        except TimeoutException: # success
            
            driver_hash[id] = driver
            
            return True, NO_PROBLEM
    except Exception as e:
        print(e)
        driver.close()
        driver.quit()
        return False, EXCEPTION
    driver.close()
    driver.quit()
    return True, EXCEPTION
Beispiel #12
0
 def step_switch_to_alert(self, value1, value2):
     prompt = Alert(self.driver)
     prompt.send_keys(value1)
     prompt.send_keys(value2)
     prompt.accept()
Beispiel #13
0
def accept_alert(step):
    Alert(world.browser).accept()
Beispiel #14
0
def alert():
    try:
        da = Alert(driver)
        da.accept()
    except:
        "There is no alert"
Beispiel #15
0
 def alert(self):
     alert = Alert(self.driver).text
     return alert
Beispiel #16
0
                    xpath = f'/html/body/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td[{col}]'
                    novo_dia = p.driver.find_element_by_xpath(xpath)
                    novo_dia_texto = novo_dia.text.replace('__', '').strip()
                    if len(novo_dia_texto) == 0:
                        break

                    col += 1

                p.logger.info(
                    f'Uma nova data será inserida na coluna {col-1}.')

                # é preciso clicar na célula correspondente ao dia para
                # ativar um prompt javascript e preencher com o dia
                try:
                    novo_dia.click()
                    alert = Alert(p.driver)
                    alert.send_keys(dia)
                    alert.accept()
                    p.logger.info(f'Inserido dia {dia} no diário.')
                except:
                    p.errorquit(
                        f'Não foi possível inserir dia {dia} no diário.')
                sleep(1)

                # clica no checkbox correspondente ao dia para
                # marcar presença a todos os alunos, por padrão
                try:
                    box_dia = p.driver.find_element_by_id('day_' +
                                                          str(col - 1))
                    box_dia.click()
                    p.logger.info('Marcando presença para os estudantes.')
Beispiel #17
0
 def switch_to_alert_accept(self):
     alert = Alert(self.driver)
     return alert.accept()
def test_first_page_cards_title(browser):
    # 평소 짱구는 요즘 새로운 사람을 만나고 싶어서 우리 서비스에 접속했다.
    # 서비스에 접속하니
    browser.get(ROOT_URL_DEVELOP)

    # 첫 화면에는 모임에 대한 정보가 보이는 카드들이 보였다.

    # 그 카드 중 하나를 자세히 살펴보니 맨 상단에는 규카츠 먹을래? 제목이 보여졌고,
    assert '규카츠 먹을래?' in browser.page_source

    # 그 아래에는 장선혁(개설자 이름)
    assert '장선혁' in browser.page_source

    # 강남(장소)
    assert '강남' in browser.page_source

    # 02/22 21:52 (시작 시간)
    assert '02/22 21:52' in browser.page_source

    # 규카츠가 맛있게 보이는 사진
    # 고려대학교 10km 이내(가까운 대학교와의 거리)
    assert '고려대학교 10km 이내' in browser.page_source

    # 5,000원~10,000원(가격대)
    assert '5,000원~10,000원' in browser.page_source
    # 들이 보인다.

    # 그 바로 하단에는 선이 그어져 있어서 왠지 서로 구분이 되는 느낌이다
    browser.find_element_by_tag_name('hr')

    # 맨 상단에는 호타루에서 우동 먹을래? 제목이 보여졌고,
    assert '호타루에서 우동 먹을래?' in browser.page_source
    # 그 아래에는 최지훈(개설자 이름)
    assert '최지훈' in browser.page_source
    # 이대(장소)
    assert '이대' in browser.page_source
    # 02/22 22:22 (시작 시간)
    assert '02/22 22:22' in browser.page_source
    # 우동이 맛깔스럽게 보이는 사진
    # 이화여자대학교 10km 이내(가까운 대학교와의 거리)
    assert '이화여자대학교 10km 이내' in browser.page_source
    # 5,000원~10,000원(가격대)
    assert '5,000원~10,000원' in browser.page_source
    # 들이 보인다.

    # 짱구는 두 모임 중에 지훈이의 '호타루 우동 모임'에 참가하고 싶어졌다.
    # 그래서 모임 아래에 신청하기 버튼을 확인한 후,
    btn_list = browser.find_elements_by_tag_name('button')
    assert btn_list[1].text == "신청하기"

    # 신청 버튼을 눌렀더니
    btn_list[1].click()

    # 해당 모임을 신청하는 페이지로 이동하였고
    assert urljoin(ROOT_URL_DEVELOP,
                   "/meetings/2/apply/") == browser.current_url

    # 상단에 "호타루에서 우동 먹을래?" 라는 모임의 제목이 보였다.
    assert "호타루에서 우동 먹을래?" in browser.page_source

    # 이름, 성별, 연락처를 입력하라는 메세지와 입력박스가 표시된다.
    assert "이름 : " in browser.page_source
    assert "연락처 : " in browser.page_source
    assert "성별 : " in browser.page_source

    input_boxs = browser.find_elements_by_tag_name('input')

    # 그래서 짱구는 이름 칸에 '김짱구'라고 입력 했고
    input_boxs[0].send_keys('김짱구')

    # 연락처는 '010-1234-5678' 로 입력하고
    input_boxs[1].send_keys('010-1234-5678')

    # 성별은 '남성'으로 체크하고
    input_boxs[2].click()

    # 신청 버튼을 누르자
    apply_button = browser.find_element_by_tag_name('button')
    apply_button.click()

    # '신청이 완료되었습니다.' 라는 메세지가 표시됐다.
    assert "신청이완료되었습니다." in Alert(browser).text

    # 확인 버튼을 눌렀더니
    Alert(browser).accept()

    # 메인 홈페이지로 이동을 하였다
    assert urljoin(ROOT_URL_DEVELOP, '/') == browser.current_url
Beispiel #19
0
 def alert_text(self):
     alert = Alert(self.driver)
     message = alert.text  #获取警告框的text消息
     return message
    def not_test_basics(self):
        global PAGE
        current_screenshot = 1
        #reserve_path = FOLDER + "\\" + PAGE         #TO DO : REMOVE IF NOT NEEDED
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"

        driver = self.driver
        driver.delete_all_cookies()
        driver.get('https://lima.soc.port.ac.uk/')

        PAGE = "0_beta_homepage"
        #-- HOMEPAGE --

        for i in range(0, get_max_Y(driver) + 1):
            driver.execute_script("window.scrollTo(0, " + str(200 * i) + ")")
            time.sleep(WIP_SPEED)
            path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
            driver.save_screenshot(path)
            current_screenshot = current_screenshot + 1

        driver.execute_script("window.scrollTo(0, 0)")
        time.sleep(WIP_SPEED)

        PAGE = "1_logging_in"
        #-- HOMEPAGE (login) --

        current_screenshot = 1

        elem = driver.find_element_by_id("invitecode")
        elem.send_keys(INVITE_CODE)

        time.sleep(WIP_SPEED)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)

        elem.send_keys(Keys.RETURN)

        PAGE = "2_log_homepage"
        #-- HOMEPAGE (logged) --

        current_screenshot = 1

        for i in range(0, 17):
            driver.execute_script("window.scrollTo(0, " + str(200 * i) + ")")
            time.sleep(WIP_SPEED)
            path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
            driver.save_screenshot(path)
            current_screenshot = current_screenshot + 1

        driver.execute_script("window.scrollTo(0, 0)")
        time.sleep(WIP_SPEED)

        PAGE = "3_Try_a_new_metaanalysis"
        #-- TRY A NEW METAANALYSIS PAGE --

        current_screenshot = 1

        driver.find_element_by_link_text("try a new meta-analysis").click()
        driver.refresh()

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, "metaanalysis")))
        finally:
            #driver.refresh()
            if (not SILENT): print('< (meep)')

        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        driver.back()
        time.sleep(WIP_SPEED)
        Alert(driver).dismiss()
        time.sleep(WIP_SPEED)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        time.sleep(WIP_SPEED)
        driver.back()
        time.sleep(WIP_SPEED)
        Alert(driver).accept()
        time.sleep(WIP_SPEED)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        PAGE = "4_editing_locally"
        #-- see edited meta analyses and papers --

        current_screenshot = 1

        driver.find_element_by_link_text(
            "see the meta-analyses and papers you've edited locally").click()
        driver.refresh()

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, "personalinfo")))
        finally:
            #driver.refresh()
            if (not SILENT): print('< (meep)')

        time.sleep(WIP_SPEED)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        time.sleep(WIP_SPEED)
        driver.back()
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        PAGE = "5_misinformation_effect"
        #-- See misinformation paper --

        current_screenshot = 1

        driver.find_element_by_link_text("Misinformation effect").click()
        driver.refresh()

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, "metaanalysis")))
        finally:
            #driver.refresh()
            if (not SILENT): print('< (meep)')

        for i in range(0, get_max_Y(driver) + 1):
            driver.execute_script("window.scrollTo(0, " + str(200 * i) + ")")
            time.sleep(WIP_SPEED)
            path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
            driver.save_screenshot(path)
            current_screenshot = current_screenshot + 1

        driver.execute_script("window.scrollTo(0, 0)")
        time.sleep(WIP_SPEED)

        time.sleep(WIP_SPEED)
        driver.back()
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        PAGE = "6_simple_testing_metaanalysis"
        #-- See Simple testing metaanalysis paper --

        current_screenshot = 1

        driver.find_element_by_link_text("Simple testing metaanalysis").click()
        driver.refresh()

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, "metaanalysis")))
        finally:
            driver.refresh()
            if (not SILENT): print('< (meep)')

        for i in range(0, 4):
            driver.execute_script("window.scrollTo(0, " + str(200 * i) + ")")
            time.sleep(WIP_SPEED)
            path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
            driver.save_screenshot(path)
            current_screenshot = current_screenshot + 1

        driver.execute_script("window.scrollTo(0, 0)")
        time.sleep(WIP_SPEED)

        time.sleep(WIP_SPEED)
        driver.back()
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
 def dismiss_alert(self):
     Alert(self.driver).dismiss()
    def test_scenar2(self):

        global PAGE
        PAGE = "8_scenar_2_"
        current_screenshot = 1

        driver = self.driver
        driver.delete_all_cookies()
        driver.get('https://lima.soc.port.ac.uk/')

        elem = driver.find_element_by_id("invitecode")
        elem.send_keys(INVITE_CODE)

        time.sleep(WIP_SPEED)

        elem.send_keys(Keys.RETURN)
        time.sleep(WIP_SPEED)

        driver.find_element_by_link_text("try a new meta-analysis").click()
        driver.refresh()

        try:
            WebDriverWait(driver, 10).until(
                EC.presence_of_element_located((By.ID, "metaanalysis")))
        finally:
            #driver.refresh()
            if (not SILENT): print('< (meep)')
            time.sleep(2)

        title = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id = 'metaanalysis']/header/h1[contains(@class, 'title editing oneline validationerror')]"
        )
        title.send_keys("f")

        time.sleep(WIP_SPEED)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        #title.send_keys(Generate_foo_name())
        title.send_keys("oo")
        title.send_keys(Keys.RETURN)

        time.sleep(WIP_SPEED)

        driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id ='metaanalysis']/header/button[contains(@class, 'titlerename editing')]"
        ).click()
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        author = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id ='metaanalysis']/div[contains(@class, 'published popupboxtrigger')]/div[contains(@class, 'edithighlight')]/span[contains(@class, 'value editing oneline')]"
        )
        author.send_keys("Mr Sheep")
        time.sleep(WIP_SPEED)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        description = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id ='metaanalysis']/p[contains (@class, 'description edithighlight')]/span[contains(@class, 'value editing')]"
        )
        description.send_keys("Mr Sheep's tests")
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        tag1 = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id ='metaanalysis']/header/ul[contains(@class, 'tags empty')]/li[contains(@class, 'addtag editing')]"
        )
        tag1.click()
        tag1Edit = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id ='metaanalysis']/header/ul[contains(@class, 'tags empty')]/li[contains(@class, 'new')]/span[contains(@class, 'tag')]"
        )
        tag1Edit.send_keys("Mr Sheep")
        tag1Edit.send_keys(Keys.RETURN)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you')]/section[@id = 'metaanalysis']/div[@class = 'experiments']/table[@class = 'experiments']/tbody/tr[contains(@class, 'add')]/th/button[contains(@class, 'add notunpin not-unsaved')]"
        ).click()
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"

        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        paperName = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you boxpinned')]/section[@id = 'metaanalysis']/div[@class = 'experiments']/table[@class = 'experiments']/tbody/tr[contains(@class, 'row paperstart')]/th[contains(@class, 'popupboxtrigger popupboxhighlight papertitle pinned')]/div[contains(@class, 'paperinfo popupbox pinned')]/header/p[contains(@class, 'paptitle editing')]"
        )
        paperName.click()
        paperName.send_keys("Sheep1-f" + Generate_foo_name())
        paperName.send_keys(Keys.RETURN)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"

        expName = driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing new page-about-you boxpinned')]/section[@id = 'metaanalysis']/div[@class = 'experiments']/table[@class = 'experiments']/tbody/tr[contains(@class, 'row paperstart')]/th[contains(@class, 'popupboxtrigger popupboxhighlight experimenttitle pinned')]/div[contains(@class, 'experimentinfo popupbox pinned')]/header/p/span[contains(@class, 'exptitle editing')]"
        )
        expName.click()
        expName.send_keys("White sheeps")
        time.sleep(WIP_SPEED)

        expName.send_keys(Keys.RETURN)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        expName.clear()
        expName.send_keys("WhiteSheeps")
        expName.send_keys(Keys.RETURN)
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        time.sleep(10)

        driver.back()
        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1

        driver.find_element_by_link_text(
            "see the meta-analyses and papers you've edited locally").click()
        time.sleep(WIP_SPEED)

        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
        time.sleep(WIP_SPEED)

        driver.find_element_by_xpath(
            "/html/body[contains(@class, 'editing page-about-you')]/section[@id='personalinfo']/p[contains(@class, 'localediting resetlocalstorage')]"
        ).click()

        Alert(driver).accept()

        time.sleep(5)

        path = FOLDER + "\\" + PAGE + str(current_screenshot) + ".png"
        driver.save_screenshot(path)
        current_screenshot = current_screenshot + 1
 def get_alert(self):
     """Returns instance of selenium.webdriver.common.alert.Alert"""
     return Alert(self)
Beispiel #24
0

if __name__ == '__main__':
    engine = create_engine(
        "mysql+pymysql://eums:[email protected]:3306/eums-poi?charset=utf8mb4",
        encoding='utf8',
        pool_size=20,
        pool_recycle=3600,
        connect_args={'connect_timeout': 1000000})

    crawling_url = 'http://mygeoposition.com/'
    driver = webdriver.Chrome(
        'C:\\Users\\1906182\\Downloads\\chromedriver')  #크롬 드라이버 설치 필요
    driver.get(crawling_url)
    driver.implicitly_wait(5)
    Alert(driver).accept()  #알람 수락

    for i in range(87):
        print(i)
        query = '''
        select a.ID, CO_NAME_R, ADDR, LATITUDE, LONGITUDE, REP_PHONE_NUM, MSISDN
        from MEUMS_COMPANY a left join MEUMS_COM_ADD_PHONE_NUM b on a.ID = b.CO_ID and a.REP_PHONE_NUM != b.MSISDN
        where a.ID > {} and a.ID <= {}'''.format(i * 100000, (i + 1) * 100000)

        my_company_list = pd.read_sql_query(query, engine)

        columns = [str(my_company_list.columns)]
        result = []
        print(len(my_company_list))
        if len(my_company_list) == 0: continue
 def setUp(self):
     #Initialize webdriver
     self.driver = webdriver.Chrome()
     self.driver.get('http://127.0.0.1:5500/test_stub.html')
     self.alert = Alert(self.driver)
'''
Created on Jan 29, 2019

@author: vkhoday
'''

from selenium.webdriver.common.alert import Alert
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoAlertPresentException

txt_scr = '//*[@id="search_str"]'

driver = webdriver.Chrome(
    'C:/Users/DELL/eclipse-workspace/CDI/WebDriver/chromedriver')

driver.get('https://www.moneycontrol.com')
ActionChains(driver).pause(3)
driver.maximize_window()
driver.find_element_by_xpath(txt_scr).send_keys(Keys.ENTER)
try:
    txt_msg = Alert(driver).text
    print(txt_msg)
except:
    NoAlertPresentException

assert len(txt_msg) > 0
Alert(driver).accept()
Beispiel #27
0
#ポップアップアラート処理のための例外処理
#納品日が同日の商品の入力など、入力間違いを確認するためのランダムなアラーを処理
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import NoAlertPresentException
from selenium.webdriver.common.alert import Alert

#ポップアップアラートが表示された時の処理
try:
	#セーブの段階でアラートが表示されることがあるため例外処理を行う
	save = browser.find_element_by_xpath('xパス')
	save.click()
	Alert(browser).accept()
	print("アラートが表示され、許可しました")
	#ページを遷移させる
	back_page = browser.find_element_by_link_text('aリンクのテキスト')
	back_page.click()
	#ページが読み込まれるまで待機
	wait.until(ec.presence_of_all_elements_located)

#ポップアップアラートが表示されない時の処理
except NoAlertPresentException:
	#ページを遷移させる
	back_page = browser.find_element_by_link_text('aリンクのテキスト')
	back_page.click()
	#ページが読み込まれるまで待機
	wait.until(ec.presence_of_all_elements_located)
# 소득데이터를 수집

# 셀레니움 시작을 위한 크롬 드라이버를 설정.
chromeOptions = webdriver.ChromeOptions()
prefs = {
    "download.default_directory": "/home/webserver/data/raw_data/income_data"
}
chromeOptions.add_experimental_option("prefs", prefs)
chromeOptions.add_argument("--no-snadbox")
chromedriver = "/usr/local/bin/chromedriver"
driver = webdriver.Chrome(executable_path=chromedriver,
                          chrome_options=chromeOptions)
# 사이트로 이동.
driver.get("http://oasis.krei.re.kr/analyzer/income.do")
driver.implicitly_wait(7)
da = Alert(driver)

#기간설정
driver.find_element_by_css_selector('#sYear > option:nth-child(24)').click()
driver.find_element_by_css_selector('#eYear > option:nth-child(1)').click()

#충남, 전남을 선택.
driver.find_element_by_css_selector(
    '#spancode2 > dd > ol > li:nth-child(10) > label').click()
driver.find_element_by_css_selector(
    '#spancode2 > dd > ol > li:nth-child(5) > label').click()

time.sleep(7)
# 소득, 조수입을 먼저 선택해서 저장
driver.find_element_by_css_selector(
    '#spancode1 > dd > ol.last > li:nth-child(2)').click()
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.alert import Alert
"""
Vamos levantar um http server com o comando abaixo:
python -m http.server --bind 127.0.0.1 8083
"""

driver = webdriver.Chrome()
driver.maximize_window

# windows path
driver.get("http://127.0.0.1:8083/html/alert.html")

# linux path
# driver.get("http://127.0.0.1:8083/alert_tests/html/alert.html")
driver.implicitly_wait(10)

test = driver.find_element("id", "alert")
test.click()
sleep(5)
alert = Alert(driver)
alert.accept()
Beispiel #30
0
#크롬 driver 위치

chromedriver = "D:\PTN\chromedriver.exe"
#headless 모드 넣긴했는데 dc에서 오류나서 못씀
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1920x1080')
options.add_argument("disable-gpu")
#headless mode 그대로 하면 dc접속 아예 안돼서 user-agent 변경
options.add_argument(
    "user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
)

driver = webdriver.Chrome(chromedriver)
youtube = Alert(driver)
driver.implicitly_wait(2)
driver.get('https://www.dcinside.com')
driver.find_element_by_name('user_id').send_keys(dc_id)
driver.find_element_by_name('pw').send_keys(dc_pw)
driver.find_element_by_id('login_ok').click()


def upload_text(text, account, id, link):
    driver.get(Gallery)
    driver.find_element_by_name('subject').send_keys(date, "공트 업데이트")
    driver.find_element_by_id('chk_html').click()
    url = "https://twitter.com/{0}/status/{1}".format(account, id)
    driver.find_element_by_id('tx_canvas_source').send_keys(
        now, "<br>  @", account, " <br><br>", text, "<br>", link, "<br><br>",
        convert(url))