python类XPATH的实例源码

WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_element(self, selector):
        '''
        Gets element by CSS selector.

        Parameters
        ----------
        selector: str
            A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.

        Returns
        -------
        selenium.webdriver.remote.webelement.WebElement
            A selenium element object.

        '''
        elem = self.find_element(selector)
        if elem:
            return WebRunnerElement(elem._parent, elem._id, elem._w3c)
        else:
            raise NoSuchElementException
test_case_01_valid_login.py 文件源码 项目:webtesting 作者: madlenkk 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def verify_user_logged_in(selenium):
    # kdyz potrebujeme otestovat, ze na strance je nejaky konkretni element
    # el = selenium.find_element_by_xpath('//*[@id="messages"]/div/div')
    # vynechame nefunkcni identifikatory pro pripad, ze se zmeni HTML sablona
    el = selenium.find_element_by_id('messages')

    # kdyz potrebujeme zjistit, ze element obsahuje konkretni text
    assert 'Welcome back' in el.text


    # # ExplicitWait - kdyz se nahravaji veci pomoci JavaScriptu a nereloadne se cela stranka
    # WebDriverWait(selenium, 2).until(
    #     EC.text_to_be_present_in_element((By.XPATH, '//*[@id="messages"]/div/div'), 'Welcome back')
    # )

    # # kdyz potrebujeme otestovat, ze na strance neco neni
    # from selenium.common import exceptions
    # with pytest.raises(exceptions.NoSuchElementException, message='UNEXPECTED ELEMENT PRESENT'):
    #     # musi hodit vyjimku, jinak failed
    #     selenium.find_element_by_xpath('//*[@id="messages"]/div/div')
??selenium???????????.py 文件源码 项目:python3_crawl 作者: princewen 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def login():
    """??????,??????????"""
    driver.get(start_url)
    wait = WebDriverWait(driver,10)
    try:
        username = wait.until(EC.presence_of_element_located((By.ID,"loginname")))
        password = wait.until(EC.presence_of_element_located((By.XPATH,'//*[@id="pl_login_form"]/div/div[3]/div[2]/div/input')))
        username.send_keys(user)
        password.send_keys(passwd)
        btn = wait.until(EC.element_to_be_clickable((By.XPATH,'//*[@id="pl_login_form"]/div/div[3]/div[6]/a/span')))
        btn.click()
    except TimeoutException:
        print ("??")
        return
    except NoSuchElementException:
        print ("?????? ")
        return
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def find_element(self, selector):
        '''
        Finds an element by CSS/XPATH selector.

        Parameters
        ----------
        selector: str
            A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.

        Returns
        -------
        selenium.webdriver.remote.webelement.WebElement or None
            Returns an element or nothing at all

        '''
        elem = None
        try:
            if selector.startswith('/'):
                elem = self.browser.find_element_by_xpath(selector)
            else:
                elem = self.browser.find_element_by_css_selector(selector)
        except NoSuchElementException:
            pass

        return elem
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def find_elements(self, selector):
        '''
        Finds elements by CSS/XPATH selector.

        Parameters
        ----------
        selector: str
            A CSS/XPATH selector to search for. This can be any valid CSS/XPATH selector.

        Returns
        -------
        list of selenium.webdriver.remote.webelement.WebElement or list
            Returns a list of elements or empty list

        '''
        elems = []
        try:
            if selector.startswith('/'):
                elems = self.browser.find_elements_by_xpath(selector)
            else:
                elems = self.browser.find_elements_by_css_selector(selector)
        except NoSuchElementException:
            pass

        return elems
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def wait_for_presence(self, selector='', **kwargs):
        '''
        Wait for an element to be present. (Does not need to be visible.)

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.presence_of_element_located((by, selector)) or
                       EC.presence_of_elements_located((by, selector)),
                       **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def wait_for_visible(self, selector='', **kwargs):
        '''
        Wait for an element to be visible.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.visibility_of_element_located((by, selector)),
                       **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def wait_for_invisible(self, selector='', **kwargs):
        '''
        Wait for an element to be invisible.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.invisibility_of_element_located((by, selector)),
                       **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def wait_for_text(self, selector='', text='', **kwargs):
        '''
        Wait for an element to contain a specific string.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        text: str
            The string to look for. This must be precise.
            (Case, punctuation, UTF characters... etc.)
        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.text_to_be_present_in_element((by, selector),
                                                        text), **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def wait_for_text_in_value(self, selector='', text='', **kwargs):
        '''
        Wait for an element's value to contain a specific string.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        text: str
            The string to look for. This must be precise.
            (Case, punctuation, UTF characters... etc.)
        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.text_to_be_present_in_element_value((by, selector),
                                                              text), **kwargs)
WebRunner.py 文件源码 项目:PyWebRunner 作者: IntuitiveWebSolutions 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def wait_for_selected(self, selector='', selected=True, **kwargs):
        '''
        Wait for an element (checkbox/radio) to be selected.

        Parameters
        ----------
        selector: str
            A CSS selector to search for. This can be any valid CSS selector.

        selected: bool
            Whether or not the element should be selected. Default True

        kwargs:
            Passed on to _wait_for

        '''
        if selector.startswith('/'):
            by = By.XPATH
        else:
            by = By.CSS_SELECTOR
        self._wait_for(EC.element_located_selection_state_to_be((by, selector),
                                                                selected), **kwargs)
test_ui.py 文件源码 项目:integration 作者: mendersoftware 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def login(self, driver):
        if "login" not in driver.current_url:
            return
        mock_email    = auth.email
        mock_password = auth.password
        print("Logging in with credentials:")
        print("Email: " + mock_email)
        print("Password: " + mock_password)
        email_field = driver.find_element_by_id("email")
        email_field.click()
        email_field.send_keys(mock_email)
        password_field = driver.find_element_by_id("password")
        password_field.click()
        password_field.send_keys(mock_password)
        clicked = self.click_button(driver, "log in")
        if not clicked:
            clicked = self.click_button(driver, "create user")
        assert clicked
        xp = tag_contents_xpath("button", "Dashboard")
        element = self.wait_for_element(driver, By.XPATH, xp)
        assert element
test_ui.py 文件源码 项目:integration 作者: mendersoftware 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def test_authorize_all(self):
        ui_test_banner()
        driver = self.init_driver()
        self.login(driver)
        assert self.click_button(driver, "Devices")
        self.click_button(driver, "Authorize 1 device", timeout=600)
        xp = "//table/tbody[@class='clickable']/tr/td[3]/div"
        authorized_device = self.wait_for_element(driver, By.XPATH, xp, timeout=600)
        assert authorized_device
        authorized_device.click()
        timeout = time.time() + (60*5)

        while time.time() < timeout:
            time.sleep(0.2)
            if self.wait_for_element(driver, By.XPATH, xp).text == "vexpress-qemu":
                break
        else:
            raise Exception("Device never appeared for authorization")

        print("Found authorized_device: '" + authorized_device.text + "'")
        assert authorized_device.text == "vexpress-qemu"
        ui_test_success()
        self.destroy_driver(driver)
test_ui.py 文件源码 项目:integration 作者: mendersoftware 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_basic_inventory(self):
        ui_test_banner()
        driver = self.init_driver()
        self.login(driver)
        assert self.click_button(driver, "Devices")
        authorized_device = self.wait_for_element(driver, By.CSS_SELECTOR, "div.rightFluid.padding-right tbody.clickable > tr")
        assert authorized_device
        authorized_device.click()
        assert "vexpress-qemu" in authorized_device.text
        assert "mender-image-master" in authorized_device.text

        # make sure basic inventory items are there
        assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'Linux version')]")
        assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'eth0')]")
        assert self.wait_for_element(driver, By.XPATH, "//*[contains(text(),'ARM')]")
        ui_test_success()
        self.destroy_driver(driver)
HelloWorldTestBase.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def validateLink(self, url, expectedText = None, expectedTitle = None, expectedUrl = None, \
        xpathContext = None):
        xpathContext = xpathContext if xpathContext else ""
        selector = ".//{1}a[@href='{0}']".format(url, xpathContext)
        if expectedText:
            self.assertTextPresent(By.XPATH, selector, expectedText)

        totalTries = self._followLinkMaxRetries + 1
        for i in range(0, totalTries):
            try:
                self.click(By.XPATH, selector, "Click {0}".format(expectedText), \
                    expectedURL = expectedUrl if expectedUrl else url)
                break
            except TimeoutException:
                retry = i + 1 # First 'try' is not a retry
                if retry < totalTries:
                    pass
        if expectedTitle:
            self.assertTitle(expectedTitle);
webelement.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def find_element_by_xpath(self, xpath):
        """Finds element by xpath.

        :Args:
            xpath - xpath of element to locate.  "//input[@class='myelement']"

        Note: The base path will be relative to this element's location.

        This will select the first link under this element.

        ::

            myelement.find_elements_by_xpath(".//a")

        However, this will select the first link on the page.

        ::

            myelement.find_elements_by_xpath("//a")

        """
        return self.find_element(by=By.XPATH, value=xpath)
webelement.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def find_elements_by_xpath(self, xpath):
        """Finds elements within the element by xpath.

        :Args:
            - xpath - xpath locator string.

        Note: The base path will be relative to this element's location.

        This will select all links under this element.

        ::

            myelement.find_elements_by_xpath(".//a")

        However, this will select all links in the page itself.

        ::

            myelement.find_elements_by_xpath("//a")

        """
        return self.find_elements(by=By.XPATH, value=xpath)
select.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def deselect_by_visible_text(self, text):
        """Deselect all options that display text matching the argument. That is, when given "Bar" this
           would deselect an option like:

           <option value="foo">Bar</option>

           :Args:
            - text - The visible text to match against
        """
        if not self.is_multiple:
            raise NotImplementedError("You may only deselect options of a multi-select")
        matched = False
        xpath = ".//option[normalize-space(.) = %s]" % self._escapeString(text)
        opts = self._el.find_elements(By.XPATH, xpath)
        for opt in opts:
            self._unsetSelected(opt)
            matched = True
        if not matched:
            raise NoSuchElementException("Could not locate element with visible text: %s" % text)
test_webdriver.py 文件源码 项目:core-python 作者: yidao620c 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def click_page():
    driver = webdriver.Firefox()
    driver.get('http://yidao620c.github.io/archives/')
    driver.maximize_window()
    len1 = len(driver.find_elements_by_xpath(
                '//div[@class="post-archive"]/ul[@class="listing"]/li/a'))
    _log.info('????????...')
    for k in range(1, 100):
        logging.info('?{}???...'.format(k))
        for i in range(0, len1):
            l_xpath = '(//div[@class="post-archive"]/ul[@class="listing"]/li/a)[{}]'.format(i + 1)
            ele = WebDriverWait(driver, 2).until(
                EC.presence_of_element_located((By.XPATH, l_xpath))
            )
            ele.click()
            driver.back()

    _log.info('all finished.')
    driver.close()
click_page.py 文件源码 项目:core-python 作者: yidao620c 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _click_page(total_posts, pool_size, group_index):
    _log.info('?{}?: starting...'.format(group_index + 1))
    if group_index > 0 and total_posts < pool_size * group_index:
        return
    # ????????
    _driver = webdriver.PhantomJS()
    _driver.get('https://www.xncoding.com/archives/')

    global TRY_COUNT
    for k in range(1, TRY_COUNT + 1):
        # _log.info('?{}?: ?{}???...'.format(group_index + 1, k))
        for i in range(pool_size * group_index, min(pool_size * (group_index + 1), total_posts)):
            l_xpath = '(//article/header/h1[@class="post-title"]/a[@class="post-title-link"])[{}]'.format(i + 1)
            ele = WebDriverWait(_driver, 2).until(
                EC.presence_of_element_located((By.XPATH, l_xpath))
            )
            ele.click()
            WebDriverWait(_driver, 5).until(
                EC.presence_of_element_located((By.XPATH, '//div[@class="post-body"]'))
            )
            _driver.back()

    _log.info('?{}?: finished.'.format(group_index + 1))
    _driver.close()
click_page.py 文件源码 项目:core-python 作者: yidao620c 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def just_click():
    # ????????
    _driver = webdriver.PhantomJS()
    _driver.get('https://www.xncoding.com/archives/')
    # driver.maximize_window()
    posts_count = len(_driver.find_elements_by_xpath(
        '//article/header/h1[@class="post-title"]/a[@class="post-title-link"]'))
    for cc in range(1, posts_count + 1):
        l_xpath = '(//article/header/h1[@class="post-title"]/a[@class="post-title-link"])[{}]'.format(cc)
        ele = WebDriverWait(_driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, l_xpath))
        )
        _log.info('???{}???'.format(cc))
        ele.click()
        WebDriverWait(_driver, 10).until(
            EC.presence_of_element_located((By.XPATH, '//div[@class="post-body"]'))
        )
        _driver.back()
webelement.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def find_element_by_xpath(self, xpath):
        """Finds element by xpath.

        :Args:
            xpath - xpath of element to locate.  "//input[@class='myelement']"

        Note: The base path will be relative to this element's location.

        This will select the first link under this element.

        ::

            myelement.find_elements_by_xpath(".//a")

        However, this will select the first link on the page.

        ::

            myelement.find_elements_by_xpath("//a")

        """
        return self.find_element(by=By.XPATH, value=xpath)
webelement.py 文件源码 项目:flasky 作者: RoseOu 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def find_elements_by_xpath(self, xpath):
        """Finds elements within the element by xpath.

        :Args:
            - xpath - xpath locator string.

        Note: The base path will be relative to this element's location.

        This will select all links under this element.

        ::

            myelement.find_elements_by_xpath(".//a")

        However, this will select all links in the page itself.

        ::

            myelement.find_elements_by_xpath("//a")

        """
        return self.find_elements(by=By.XPATH, value=xpath)
page_objects.py 文件源码 项目:dispatch-console-tests 作者: jdanekrh 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def expand_tree(self, node_count):
        """expand_tree expands treeview (dynatree) by clicking expander arrows one by one"""
        self.wait_for_frameworks()
        WebDriverWait(self.selenium, 10).until(EC.element_to_be_clickable(self.expander_locator))
        WebDriverWait(self.selenium, 10).until(lambda _: len(self.expanders) == node_count)

        # least-work way to fight ElementNotVisibleException: Message: Cannot click on element, and
        # http://stackoverflow.com/questions/37781539/selenium-stale-element-reference-element-is-not-attached-to-the-page-document/38683022
        def loop():
            self.wait_for_frameworks()
            for expander in self.expanders:  # type: WebElement
                node = self.retry_on_exception(NoSuchElementException, lambda: expander.find_element(By.XPATH, './..'))
                if self.is_expanded(node):
                    continue
                self.wait_for_frameworks()
                expander.click()
                self.wait_for_frameworks()
        self.retry_on_exception(StaleElementReferenceException, loop)

        self.assert_tree_expanded()
book_fetcher.py 文件源码 项目:PSpiderDemos 作者: xianhu 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def url_fetch(self, url, keys, critical, fetch_repeat):
        try:
            logging.warning("-------------------------------")
            if keys[0] == "detail":
                logging.warning("fetch %s", url)
                x_str = "//*[@id='detail'][contains(@isloaded, '1')]"
                self.driver.get(url)
                element_present = EC.presence_of_element_located((By.XPATH, x_str))
                WebDriverWait(self.driver, 60).until(element_present)
        except:
            logging.warning("Unexpected error: %s", sys.exc_info()[0])
            #self.clear_session()
            return 0, ""
        response = self.driver.page_source
        if not response:
            logging.warning("not response %s", response)
            return 0, ""
        logging.warning("fetch done!")
        return 1, response
request.py 文件源码 项目:spider-lianjia 作者: longxiaofei 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_total_page(browser, url):
    browser.get(url)
    try:
        time.sleep(4)
        total_room = browser.find_element_by_xpath('/html/body/div[4]/div[1]/div[2]/h2/span').text
        if not total_room:
            return None
        if int(total_room) <= 30:
            return 1
        total = WebDriverWait(browser, 30).until(
                EC.presence_of_element_located((By.XPATH, "/html/body/div[4]/div[1]/div[7]/div[2]/div/a[last()]"))
            )
        if not total.text.isdigit():
            total_page = browser.find_element_by_xpath('/html/body/div[4]/div[1]/div[7]/div[2]/div/a[last()-1]').text
        else:
            total_page = total.text
        return total_page
    except TimeoutException as e:
        print('????????25??????')
        time.sleep(25)
        return get_total_page(url)
test_case_02_remove_from_basket_empty.py 文件源码 项目:webtesting 作者: madlenkk 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def step_03_check_basket_is_empty(selenium):
    # //*[@id="messages"]/div[2]/p
    # pytest.set_trace()
    # el = selenium.find_element_by_id('messages')
    # import time
    # time.sleep(1)
    # assert 'Your basket is now empty' in el.text

    WebDriverWait(selenium, 2).until(
        EC.text_to_be_present_in_element(
            # (By.ID, 'messages'),
            (By.XPATH, '//p[contains(text(),"Your basket is now empty")]'),
            'Your basket is now empty'
         )
    )

    # empty_alert = selenium.find_element(By.XPATH,'//p[contains(text(),"Your basket is now empty")]')
test_external_assignment_from_scores.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def setUp(self):
        """Pretest settings."""
        self.ps = PastaSauce()
        self.desired_capabilities['name'] = self.id()
        if not LOCAL_RUN:
            self.teacher = Teacher(
                use_env_vars=True,
                pasta_user=self.ps,
                capabilities=self.desired_capabilities
            )
        else:
            self.teacher = Teacher(
                use_env_vars=True
            )
        self.teacher.login()
        # go to student scores
        self.teacher.select_course(appearance='college_physics')
        self.teacher.driver.find_element(
            By.LINK_TEXT, 'Student Scores').click()
        self.teacher.wait.until(
            expect.visibility_of_element_located(
                (By.XPATH, '//span[contains(text(), "Student Scores")]')
            )
        ).click()
test_assessment errata_form_student.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def setUp(self):
        """Pretest settings."""
        self.ps = PastaSauce()
        self.desired_capabilities['name'] = self.id()
        if not LOCAL_RUN:
            self.student = Student(
                use_env_vars=True,
                pasta_user=self.ps,
                capabilities=self.desired_capabilities
            )
        else:
            self.student = Student(
                use_env_vars=True
            )
        self.student.login()
        self.student.select_course(title='College Physics with Courseware')
        self.wait = WebDriverWait(self.student.driver, Assignment.WAIT_TIME)
        self.wait.until(
            expect.visibility_of_element_located((
                By.XPATH,
                '//button[contains(@class,"practice")]'
            ))
        ).click()
        self.wait = WebDriverWait(self.student.driver, Assignment.WAIT_TIME)
        self.student.login()
clean_up_calendar.py 文件源码 项目:TestRewrite 作者: osqa-interns 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def delete_assignment(target_element, is_published):
    """
    target_element: the web element of assignment to be deleted
    """
    target_element.click()
    sleep(1)
    if is_published:
        teacher.find(
            By.ID, "edit-assignment-button"
        ).click()
        sleep(1)
    delete_button = teacher.wait.until(
        expect.element_to_be_clickable(
            (By.XPATH, '//button[contains(@class,"delete-link")]')
        )
    )
    teacher.scroll_to(delete_button)
    sleep(1)
    delete_button.click()
    teacher.find(
        By.XPATH, '//button[contains(text(), "Yes")]'
    ).click()
    sleep(1)


问题


面经


文章

微信
公众号

扫码关注公众号