import time
import self as self
from pytest import mark
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from setuptools import setup
#mark.execute
class First_Tests:
def test_first(self, setup):
driver = setup['driver']
browser = setup['browser']
driver.get("https://shuftipro.com/")
driver.maximize_window()
def header_test(self, setup):
driver = setup['driver']
# Click on solution in header
solution = driver.find_element(By.ID, "menu-item-72751")
solution.click()
if driver.current_url == "https://shuftipro.com/solutions/":
print("land on solution page.")
else:
print("land on wrong page.")
obj = First_Tests()
obj.test_first(self, setup)
obj.header_test(self, setup)
If I remove the "self" from parameter and run the program it showing me error that, test_first() takes 1 positional arguments but 3 were given
one of easier way would be to use webdriver from selenium
driver = webdriver.Chrome()
and remove
driver = setup['driver']
browser = setup['browser']
and then get rid of setup as parameter.
The final code will look something like this:
from pytest import mark
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
#mark.execute
class First_Tests:
def test_first(self):
driver.get("https://shuftipro.com/")
driver.maximize_window()
def header_test(self):
# Click on solution in header
solution = driver.find_element(By.ID, "menu-item-72751")
solution.click()
if driver.current_url == "https://shuftipro.com/solutions/":
print("land on solution page.")
else:
print("land on wrong page.")
obj = First_Tests()
obj.test_first()
obj.header_test()
Related
`
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from time import sleep
import os
login_page = "https://fap.fpt.edu.vn/Default.aspx"
# page = "https://fap.fpt.edu.vn/Report/ScheduleOfWeek.aspx"
email = ""
password = ""
options = Options()
options.add_argument("--window-size=1920,1080")
options.binary_location = "C:\Program Files\Google\Chrome\Application\chrome.exe"
driver = webdriver.Chrome(options = options)
driver.get(login_page)
login1 = driver.find_element("xpath","//div[#class='abcRioButtonContentWrapper']").click()
driver.find_element(By.NAME, "identifier").send_keys(email)
sleep(3)
driver.find_element(By.ID, "identifierNext").click()
sleep(2)
driver.find_element(By.NAME, "password").send_keys(password)
sleep(2)
driver.find_element(By.ID, "passwordNext").click()
sleep(999999)
`
I believe i chose the right By.NAME ( "indentifier" ) but the code still not work and return message no such element.
I tried to change the syntax, using xpath change By.NAME to By.ID but it still not work
Google login page opens in a new window. So you need to switch to this window before interacting with it. So you need to use this code (the first and the last lines are from your code and between is the part you need to add):
login1 = driver.find_element("xpath","//div[#class='abcRioButtonContentWrapper']").click()
windows = driver.window_handles
driver.switch_to.window(windows[1])
driver.find_element(By.NAME, "identifier").send_keys(email)
And after you've finished with the login you will need to switch back to the main window. To do that you can use this code:
driver.switch_to.window(windows[0])
And then work with the content of the page
No, don't use name of jsname here, because they get filled with random data.
Just find your Google account name or your email address by text and click it:
userAccount = driver.find_element_by_xpath("//*[text()='YourGoogleAccountName']")
userAccount.click()
I have some issue with docker selenium. For example, I have tried it on local selenium using operadriver, so redirecting to another page, after submit form, was working.I want to see this result also in django selenium test, but I've just get selenium.common.exceptions.TimeoutException: Message: in waiting when url will change.
This is my test code
import os
import socket
import shutil
# from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from django.test import LiveServerTestCase
from django.conf import settings
# Create your tests here.
class LandFormTest(LiveServerTestCase):
host = socket.gethostbyname(socket.gethostname())
def setUp(cls):
selenium_url = 'http://selenium:4444/wd/hub'
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--ignore-certificate-errors")
# options.add_argument("My user agent")
options.add_argument(f"window-size=1920,1080")
cls.driver = webdriver.Remote(
command_executor=selenium_url,
desired_capabilities=DesiredCapabilities.CHROME,
options=options
)
def test_form(self):
try:
driver = self.driver
domain = self.live_server_url.split('//')[1].split(':')[0]
if not settings.BASE_DIR.joinpath(f'templates/lands/{domain}').is_dir():
src = f'templates/lands/quantum.localhost'
dest = f'templates/lands/{domain}'
shutil.copytree(src, dest)
driver.get(f'{self.live_server_url}/api/v1/test/?ai=2&gi=5')
user_firstname = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "firstname"))
)
current_url = driver.current_url
user_firstname = driver.find_element(By.NAME, 'firstname')
user_lastname = driver.find_element(By.NAME, 'lastname')
user_email = driver.find_element(By.NAME, 'email')
user_phone = driver.find_element(By.NAME, 'phone')
user_firstname.send_keys('test')
user_lastname.send_keys('test')
user_email.send_keys('test#gmail.com')
user_phone.send_keys('+(846)411-36-00')
user_phone.submit()
WebDriverWait(driver, 10).until(EC.url_changes(current_url))
print(driver.current_url)
print(driver.page_source)
assert 'Hello World' in driver.page_source
except Exception as e:
raise(e)
def tearDown(self):
self.driver.quit()
My /api/v1/test/ url get static and template in folder by domain name, so I copy the default folder "quantum.localhost" and rename it to ip of docker. The main problem is that is working locally with driver, but not with docker and django. Want to notice that I am also tried to use firefox selenium. Thanks for help!
I'm pretty new in programming so I might be an easy question, but I don't understand why the browsers opened by Selenium closes at the end of the code.
from lib2to3.pgen2 import driver
from selenium import webdriver
def Online_PLatform():
Driver = webdriver.Chrome()
Driver.get('https://elearningmarikina.ph/')
Gmail = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[1]/input')
Gmail.send_keys('958rectin#depedmarikina.com')
Pass = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[2]/input')
Pass.send_keys('33112')
Button = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[3]/button')
Button.click()
You can use 2 approaches in order to keep you driver open.
1.
Add the 'detach' option to your driver settings:
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("detach", True)
Simply add a delay at the end of your test code (less elegant approach but more simple)
from lib2to3.pgen2 import driver
from selenium import webdriver
import time
def Online_PLatform():
Driver = webdriver.Chrome()
Driver.get('https://elearningmarikina.ph/')
Gmail = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[1]/input')
Gmail.send_keys('958rectin#depedmarikina.com')
Pass = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[2]/input')
Pass.send_keys('33112')
Button = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[3]/button')
Button.click()
time.sleep(50)
This is because after the all functions, The code stops running and that's why selenium exits.
You can use the time module to delay.
import time
from lib2to3.pgen2 import driver
from selenium import webdriver
def Online_PLatform():
Driver = webdriver.Chrome()
Driver.get('https://elearningmarikina.ph/')
Gmail = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[1]/input')
Gmail.send_keys('958rectin#depedmarikina.com')
Pass = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[2]/input')
Pass.send_keys('33112')
Button = Driver.find_element_by_xpath('/html/body/div[1]/div/div/div[1]/div[2]/div/div/form/div[3]/button')
Button.click()
time.sleep(50) #---> 50 second delay
I am using send_keys command without using key_up, and I am inclined to think that upon calling ActionChains.reset_actions() the keys that I was send_keying should be released, but alas, they are not.
I tried using key_up, but it is only for modifiers, so it did not help.
EDIT: Creating new ActionChains object each time process() is called did the trick, but I still expected reset_actions to do the same.
import os
import time
import selenium
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
my_path = os.path.dirname(os.path.abspath(__file__))
driver_path = my_path + "//chromedriver.exe"
bot_wakeword = "BOT"
class Bot:
def __init__(self):
# Using Chrome as our browser.
self.driver = webdriver.Chrome(driver_path)
# Open Gridworlds.
self.driver.get('*my url here')
# Waiting till our page loads.
WebDriverWait(self.driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME,"frame")))
# Finding a div rps-wrapper with events in it. The events element is our chat.
self.chat = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.rps-wrapper>ul#events")))
# So we surely are on the page.
self.chat.click()
self.actions = ActionChains(self.driver)
def get_last_message(self):
messages = self.chat.find_elements_by_tag_name("li")
return messages[len(messages) - 1].get_attribute("innerHTML")
def parse_command_from_message(self, message):
wake_word = message.find(bot_wakeword)
if(wake_word >= 0):
if(message.find("up") >= 0):
self.actions.send_keys(Keys.ARROW_UP)
elif(message.find("right") >= 0):
self.actions.send_keys(Keys.ARROW_RIGHT)
elif(message.find("down") >= 0):
self.actions.send_keys(Keys.ARROW_DOWN)
elif(message.find("left") >= 0):
self.actions.send_keys(Keys.ARROW_LEFT)
def process(self):
self.actions.reset_actions()
self.parse_command_from_message(self.get_last_message())
self.actions.perform()
bots = []
for i in range(1):
bots.append(Bot())
while(True):
for bot in bots:
bot.process()```
I expected reset_actions to release all keys that I previously send_keyed, but it did not release them.
I am having trouble with Selenium lately.
I'm trying to get all the URL from
http://cimex.co/resources.html
and open it on a new tab.
I'm trying to achieve with this code:
import selenium, os
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://cimex.co/resources.html')
links = browser.find_elements_by_css_selector('a[href^="https"]')
links[0].click()
While I am facing another problem is there any chance if it detects Firefox running just open the URL in a new tab rather than opening Firefox as a new app.
Thanks.
Sorry for my bad English.
I already had to do that, it was with the ChromeDriver, I cannot say if it will works the same with Firefox, but here is the code:
def Browser(object):
def __init__(self):
self.driver = webdriver.Chrome(driver_path)
self._tabs = {'default': self.driver.window_handles[0]}
def new_tab(self, name):
'''
Create new tab `name`.
name New tab name
'''
self.driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + 't')
self._tabs[name] = self.driver.window_handles[-1]
def switch_tab(self, name):
'''
Switch to given tab.
name Tab name to switch
'''
self.driver.switch_to_window(self._tabs[name])
browser = Browser()
browser.driver.get('http://cimex.co/resources.html')
links = browser.driver.find_elements_by_css_selector('a[href^="https"]')
url = links[0].get_attribute('href')
# open new tab
browser.new_tab(url, 'tab-name')
# switch to new tab
browser.switch_tab('tab-name')
# back to default tab
browser.switch_tab('default')
You can try this code :
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Firefox(executable_path = r'D:/Automation/geckodriver.exe')
browser.get("http://cimex.co/resources.html")
wait = WebDriverWait(browser, 30)
main_tab = browser.current_window_handle
print(main_tab)
links = browser.find_elements_by_tag_name('a')
size = len(links)
print ('this the length of list:',size)
i = 0
while i<size:
ActionChains(browser).key_down(Keys.CONTROL).click(links[i]).key_up(Keys.CONTROL).perform()
browser.switch_to_window(main_tab)
i=i+1;
if i >= size:
break
print(" here you quit the driver as per your wish")
from selenium import webdriver
browser = webdriver.Firefox(gecko driver location)
browser.get('http://cimex.co/resources.html')
links = browser.find_elements_by_css_selector('a[href^="https"]')
for link in links:
link.click()