示例#1
0
Drivers necessários para cada navegador. É necessário que eles estejam como vari
áveis de ambiente.
https://www.selenium.dev/documentation/en/webdriver/driver_requirements/
    
"""
from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import WebDriverWait as wdw
from selenium.webdriver.support import expected_conditions as ec
driver = Firefox()  # Ou outro navegador, também podemos fazer with Firefox()
#as driver

# Navegação do Browser
driver.get("https://github.com")  # Insere o site que você deseja ir
driver.current_url
driver.back()  # Faz a opção de voltar para página anterior
driver.forward()  # Avança no histórico
driver.refresh()
driver.title  # Retorna o Title do html da página
driver.close()  # Fecha a janela ou aba
driver.quit()  # Fecha o browser e finaliza a sessão

# Localizando elementos no Browser
driver.find_element_by_name(
    "q"
)  # Existem várias formas de encontrar elementos como id, tag name... busque por elements para ter uma lista
# Armazene esse elemento em uma variável e você pode iterar o processo para encontrar um elemento nessa variável
# Um web element tem o atributo text para obter o texto dele.

# Gerenciamento de Tela
driver.get_window_size(
示例#2
0
from selenium.webdriver import Firefox
from time import sleep

def find_by_text(browser, tag, text):
    elements = browser.find_elements_by_tag_name(tag) # lista
    
    for element in elements:
        if element.text == text:
            return element

browser = Firefox()
browser.get('http://selenium.dunossauro.live/aula_04_b.html')

nomes_das_caixas = ['um', 'dois', 'tres', 'quatro']

for nome in nomes_das_caixas:
    find_by_text(browser, 'div', nome).click()

for nome in nomes_das_caixas:
    sleep(0.3)
    browser.back()

for nome in nomes_das_caixas:
    sleep(0.3)
    browser.forward()
示例#3
0
# Selenium com Python #04 - Navegação e atributos
# Busca aninhada
# Atributos
# Navegação
from selenium.webdriver import Firefox
from time import sleep

driver = Firefox()

url = "http://selenium.dunossauro.live/aula_04_b.html"
driver.get(url)

sleep(2)
boxs = ["box-1","box-2","box-3","box-4"]
    
for box in boxs:
    box = driver.find_element_by_id(box)
    box.click()
    sleep(0.2)

for i in range(4):
    driver.back()
    sleep(0.4)

for i in range(4):
    driver.forward()
    sleep(0.4)
示例#4
0
class TestMaxlifeFeature(object):
    """
    Checks if the maxlife feature is working
    """
    def setup_class(self):
        """
        Setup: Open a mozilla browser, login
        """
        self.browser = Firefox()
        self.browser.get('http://*****:*****@value='Logout']")
        except NoSuchElementException:
            raise ValueError(
                "Can't login!!! Create a user 'foo' with the permissions"
                "'read' and 'create' in your PERMISSIONS in the config")

    def teardown_class(self):
        """
        Tear down: Close the browser
        """
        self.browser.quit()

    @property
    def page_body_lowercase(self):
        return self.browser.find_element_by_tag_name("body").text.lower()

    def test_unit_input_exists(self):
        unit_input = self.browser.find_element_by_name("maxlife-unit")
        assert unit_input is not None
        value_input = self.browser.find_element_by_name("maxlife-value")
        assert value_input is not None

    def fill_form(self):
        """
        Fills test values to the form and submits it
        :return: tuple(filename, pasted_text)
        """
        filename = "test.txt"
        text_to_paste = "This is test"
        paste_input = self.browser.find_element_by_id("formupload")
        paste_input.send_keys(text_to_paste)
        filename_input = self.browser.find_element_by_id("filename")
        filename_input.send_keys(filename)
        contenttype_input = self.browser.find_element_by_id("contenttype")
        contenttype_input.send_keys("text/plain")
        contenttype_input.send_keys(Keys.ENTER)
        time.sleep(.2)  # give some time to render next view
        return filename, text_to_paste

    def delete_current_file(self):
        self.browser.find_element_by_id("del-btn").click()
        time.sleep(.2)
        self.browser.find_element_by_class_name("bootbox-accept").click()

    def test_paste_keep_forever(self):
        self.browser.find_element_by_xpath(
            "//select[@name='maxlife-unit']/option[@value='forever']").click()
        value_input = self.browser.find_element_by_name("maxlife-value")
        value_input.clear()
        value_input.send_keys(1)
        self.fill_form()
        assert "max lifetime: forever" in self.page_body_lowercase
        self.delete_current_file()

    def test_paste_keep_minutes(self):
        self.browser.find_element_by_xpath(
            "//select[@name='maxlife-unit']/option[@value='minutes']").click()
        value_input = self.browser.find_element_by_name("maxlife-value")
        value_input.clear()
        value_input.send_keys(1)
        self.fill_form()
        assert "max lifetime: forever" not in self.page_body_lowercase
        self.delete_current_file()

    def test_filename_gets_displayed(self):
        filename, _ = self.fill_form()
        assert filename.lower() in self.page_body_lowercase
        self.delete_current_file()

    def test_pasted_text_gets_displayed(self):
        _, pasted_text = self.fill_form()
        self.browser.find_element_by_id("inline-btn").click()
        assert pasted_text.lower() in self.page_body_lowercase
        self.browser.back()
        self.delete_current_file()

    @pytest.mark.slow
    def test_file_gets_deleted_after_expiry_time(self):
        self.browser.find_element_by_xpath(
            "//select[@name='maxlife-unit']/option[@value='minutes']").click()
        value_input = self.browser.find_element_by_name("maxlife-value")
        value_input.clear()
        value_input.send_keys(1)
        self.fill_form()
        time.sleep(61)
        self.browser.find_element_by_id("inline-btn").click()
        assert "not found" in self.page_body_lowercase
示例#5
0
class TestMaxlifeFeature(object):
    """
    Checks if the maxlife feature is working
    """

    def setup_class(self):
        """
        Setup: Open a mozilla browser, login
        """
        self.browser = Firefox()
        self.browser.get('http://*****:*****@value='Logout']")
        except NoSuchElementException:
            raise ValueError("Can't login!!! Create a user 'foo' with the permissions"
                             "'read' and 'create' in your PERMISSIONS in the config")

    def teardown_class(self):
        """
        Tear down: Close the browser
        """
        self.browser.quit()

    @property
    def page_body_lowercase(self):
        return self.browser.find_element_by_tag_name("body").text.lower()

    def test_unit_input_exists(self):
        unit_input = self.browser.find_element_by_name("maxlife-unit")
        assert unit_input is not None
        value_input = self.browser.find_element_by_name("maxlife-value")
        assert value_input is not None

    def fill_form(self):
        """
        Fills test values to the form and submits it
        :return: tuple(filename, pasted_text)
        """
        filename = "test.txt"
        text_to_paste = "This is test"
        paste_input = self.browser.find_element_by_id("formupload")
        paste_input.send_keys(text_to_paste)
        filename_input = self.browser.find_element_by_id("filename")
        filename_input.send_keys(filename)
        contenttype_input = self.browser.find_element_by_id("contenttype")
        contenttype_input.send_keys("text/plain")
        contenttype_input.send_keys(Keys.ENTER)
        time.sleep(.2)  # give some time to render next view
        return filename, text_to_paste

    def delete_current_file(self):
        self.browser.find_element_by_id("del-btn").click()
        time.sleep(.2)
        self.browser.find_element_by_class_name("btn-primary").click()

    def test_paste_keep_forever(self):
        self.browser.find_element_by_xpath("//select[@name='maxlife-unit']/option[@value='forever']").click()
        value_input = self.browser.find_element_by_name("maxlife-value")
        value_input.clear()
        value_input.send_keys(1)
        self.fill_form()
        assert "max lifetime: forever" in self.page_body_lowercase
        self.delete_current_file()

    def test_paste_keep_minutes(self):
        self.browser.find_element_by_xpath("//select[@name='maxlife-unit']/option[@value='minutes']").click()
        value_input = self.browser.find_element_by_name("maxlife-value")
        value_input.clear()
        value_input.send_keys(1)
        self.fill_form()
        assert "max lifetime: forever" not in self.page_body_lowercase
        self.delete_current_file()

    def test_filename_gets_displayed(self):
        filename, _ = self.fill_form()
        assert filename.lower() in self.page_body_lowercase
        self.delete_current_file()

    def test_pasted_text_gets_displayed(self):
        _, pasted_text = self.fill_form()
        self.browser.find_element_by_id("inline-btn").click()
        assert pasted_text.lower() in self.page_body_lowercase
        self.browser.back()
        self.delete_current_file()

    @pytest.mark.slow
    def test_file_gets_deleted_after_expiry_time(self):
        self.browser.find_element_by_xpath("//select[@name='maxlife-unit']/option[@value='minutes']").click()
        value_input = self.browser.find_element_by_name("maxlife-value")
        value_input.clear()
        value_input.send_keys(1)
        self.fill_form()
        time.sleep(61)
        self.browser.find_element_by_id("inline-btn").click()
        assert "not found" in self.page_body_lowercase
示例#6
0
class Main:

    # ------初始化,打开浏览器和易班登陆页----------
    def initWebkit(self):
        self.browser = Firefox()
        # self.browser.implicitly_wait(10)  # 隐性等待
        self.browser.get('https://www.yiban.cn/login')

    # ------模拟登陆易班进入首页----------
    def loginModel(self):
        self.browser.find_element_by_id("account-txt").send_keys('17376579036')  # 伟杰15397035243  王颢霖15968869844   17376579036
        self.browser.find_element_by_id("password-txt").send_keys('qq13931975931')  # 720237lwj   wangyifei123   qq13931975931
        self.browser.find_element_by_id("login-btn").click()
        sleep(3)
        try:
            captcha_img = self.browser.find_element_by_css_selector(".captcha")
            str = input('是否继续')
            self.browser.find_element_by_id("login-btn").click()
        except:
            print('直接进入首页')

    # ------模拟操作之签到(一天只能进行一回操作,有效次数一回)----------
    def signInModel(self):
        try:
            WebDriverWait(self.browser, 20, 0.5).until_not(EC.presence_of_element_located((By.ID, 'tool-newbie')))
            self.browser.find_element_by_id("tool-sign").click()
            WebDriverWait(self.browser, 3, 0.5).until(EC.visibility_of_element_located((By.ID, 'sign-survey')))
            self.browser.find_element_by_xpath("//div[@id='sign-survey']/dl/dd[1]/i").click()
            self.browser.find_element_by_css_selector(".dialog-confirm").click()
        except:
            return True

    # ------模拟操作之发布博文(一天能进行无数次,有效次数两次)----------
    def publishBlogModel(self):
        WebDriverWait(self.browser, 20, 0.5).until(EC.element_to_be_clickable((By.ID, 'y-publish')))
        self.browser.find_element_by_id("y-publish").click()  # 点击发布按钮
        WebDriverWait(self.browser, 20, 0.5).until(
            EC.visibility_of_element_located((By.CLASS_NAME, 'font-publish-blog')))
        self.browser.find_element_by_css_selector(".font-publish-blog").click()  # 点击博文按钮,这时产生新窗口
        self.handles = self.browser.window_handles  # 获取所有窗口句柄
        self.browser.switch_to_window(self.handles[1])  # 定位博文窗口
        WebDriverWait(self.browser, 20, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'blog-title')))
        self.browser.find_element_by_class_name('blog-title').send_keys('每日好句')  # 填写题目
        WebDriverWait(self.browser, 5, 0.5).until(EC.visibility_of_element_located((By.ID, 'ueditor_0')))
        frame = self.browser.find_element_by_id('ueditor_0')  # 获取编辑器frame
        self.browser.switch_to_frame(frame)  # 切换到编辑器frame
        text = '喜欢白色,单纯,天真,当然,在那暇净的背后也掩饰着死亡的苍凉。'
        self.browser.find_element_by_tag_name('body').send_keys(text)  # 填写文章内容
        self.browser.switch_to_default_content()  # 回退到博文主frame
        # 由于单选框被遮挡,所以使用添加执行js脚本的方法点击单选框
        self.browser.execute_script('document.getElementById(\'sync-ymm\').click()')
        self.browser.find_element_by_class_name('js-submit').click()  # 点击提交按钮
        self.browser.close()  # 关闭博文网页
        self.browser.switch_to_window(self.handles[0])  # 选中易班首页窗口

    # ------模拟操作之发布动态(一天能进行无数次,有效次数两次)----------
    def pulishTrendsModel(self):
        WebDriverWait(self.browser, 5, 0.5).until(EC.element_to_be_clickable((By.ID, 'y-publish')))
        self.browser.find_element_by_id("y-publish").click()  # 点击发布按钮
        WebDriverWait(self.browser, 5, 0.5).until(
            EC.visibility_of(self.browser.find_elements_by_class_name('font-publish-feed')[1]))
        self.browser.find_elements_by_class_name('font-publish-feed')[1].click()  # 点击动态按钮,这时产生新窗口
        self.handles = self.browser.window_handles  # 获取所有窗口句柄
        self.browser.switch_to_window(self.handles[1])  # 定位动态窗口
        WebDriverWait(self.browser, 5, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'textarea')))
        self.browser.find_element_by_class_name('textarea').send_keys('今天天气真好')
        try:
            WebDriverWait(self.browser, 3, 0.5).until(
                EC.visibility_of_element_located((By.CLASS_NAME, 'guid_publish_topic')))
            self.browser.find_element_by_class_name('guid_publish_topic').click()
        except:
            print(' ')
        WebDriverWait(self.browser, 3, 0.5).until_not(
            EC.visibility_of_element_located((By.CLASS_NAME, 'guid_publish_topic')))
        self.browser.find_element_by_class_name('js-submit').click()  # 点击提交按钮
        self.browser.close()  # 关闭博文网页
        self.browser.switch_to_window(self.handles[0])  # 选中易班首页窗口

    # ------模拟操作之发布话题(一天能进行无数次,有效次数两次)----------
    def pulishTopicModel(self):
        WebDriverWait(self.browser, 10, 0.5).until(EC.element_to_be_clickable((By.ID, 'y-publish')))
        self.browser.find_element_by_id("y-publish").click()  # 点击发布按钮
        WebDriverWait(self.browser, 5, 0.5).until(
            EC.visibility_of(self.browser.find_elements_by_class_name('font-publish-topic')[1]))
        self.browser.find_elements_by_class_name('font-publish-topic')[1].click()  # 点击话题按钮,这时产生新窗口
        self.handles = self.browser.window_handles  # 获取所有窗口句柄
        self.browser.switch_to_window(self.handles[1])  # 定位话题窗口
        WebDriverWait(self.browser, 30, 0.5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'topic-title')))
        self.browser.find_element_by_class_name('topic-title').send_keys('每日好句')  # 填写题目
        WebDriverWait(self.browser, 10, 0.5).until(EC.element_to_be_clickable((By.TAG_NAME, 'iframe')))
        frame = self.browser.find_element_by_id('ueditor_0')  # 获取编辑器frame
        self.browser.switch_to_frame(frame)  # 切换到编辑器frame
        text = '喜欢白色,单纯,天真,当然,在那暇净的背后也掩饰着死亡的苍凉。'
        self.browser.find_element_by_tag_name('body').send_keys(text)  # 填写文章内容
        self.browser.switch_to_default_content()  # 回退到博文主frame
        self.browser.execute_script("window.scrollBy(0, 700)")  # 滚动屏幕
        self.browser.execute_script("arguments[0].click()",
                                    self.browser.find_elements_by_xpath('//label')[1])  # 点击发布范围单选框
        self.browser.find_element_by_class_name('js-submit').click()  # 点击提交按钮
        self.browser.close()  # 关闭博文网页
        self.browser.switch_to_window(self.handles[0])  # 选中易班首页窗口

    # ------模拟操作之更改个人信息(一天能进行无数次,一次有效)----------
    def changeInformationModel(self):
        WebDriverWait(self.browser, 10, 0.5).until(EC.element_to_be_clickable((By.XPATH, '//i[@title="个人主页"]')))
        self.browser.find_element_by_xpath('//i[@title="个人主页"]').click()  # 点击个人主页按钮
        WebDriverWait(self.browser, 10, 0.5).until(EC.element_to_be_clickable((By.ID, 'view-userinfo')))
        self.browser.find_element_by_id("view-userinfo").click()  # 点击查看个人信息按钮
        WebDriverWait(self.browser, 10, 0.5).until(EC.visibility_of_element_located(
            (By.XPATH, '//div[@id="userinfo-popup"]//div[@class="iblock last-child"]/a')))
        self.browser.find_element_by_xpath(
            '//div[@id="userinfo-popup"]//div[@class="iblock last-child"]/a').click()  # 点击个人主页按钮
        WebDriverWait(self.browser, 10, 0.5).until(EC.element_to_be_clickable((By.ID, 'nick')))
        name = self.browser.find_element_by_id('nick').get_attribute('value')
        nameList = ['笨', '蛋']
        for i in nameList:
            if (i != name):
                self.browser.find_element_by_id('nick').clear()
                self.browser.find_element_by_id('signature').clear()
                self.browser.find_element_by_id('nick').send_keys(i)
                self.browser.find_element_by_id('signature').send_keys(i)
        WebDriverWait(self.browser, 10, 1).until(EC.element_to_be_clickable((By.CLASS_NAME, 'submit')))
        self.browser.find_element_by_class_name('submit').click()
        WebDriverWait(self.browser, 10, 1).until(EC.element_to_be_clickable((By.CLASS_NAME, 'alert_sure')))
        self.browser.find_element_by_class_name('alert_sure').click()
        self.browser.back()
        self.browser.back()
    Argumentos: 
        - Navegador = Instancia do browser [firefox, chrome, etc...]
        - Conteudo que deve estar na tag
        - tag = tag onde o texto será procurado 
    """
    elementos = navegador.find_elements_by_tag_name(tag)  # lista

    for elemento in elementos:
        if elemento.text == text:
            return elemento


navegador = Firefox()
url = 'https://selenium.dunossauro.live/aula_04_b.html'

navegador.get(url)

nomes_das_caixas = ['um', 'dois', 'tres', 'quatro']

for nome in nomes_das_caixas:
    find_by_text(navegador, 'div', nome).click()

for nome in nomes_das_caixas:
    sleep(0.3)
    navegador.back()

for nome in nomes_das_caixas:
    sleep(0.3)
    navegador.forward()