Multiple test cases in one Selenium web driver instance - python

I am fairly new to programming so please be patient, but to the point.
I am creating few test cases using Selenium Web Driver, I have to check functionality of webpage to which I have to login using password and later with SMS code that I receive on my phone. I want to do this ONE TIME ONLY, so I want to use ONE instance of Web Driver for all my test cases (I know it is not recommended, but it will save a lot of time and sending 30 SMS, code from SMS is entered manually via Terminal).
My code looks something like this:
import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
class LoginTest(unittest.TestCase):
def setUp(self):
self.browser = webdriver.Safari()
def test_LoginIn(self):
browser = self.browser
(Here I am looking for buttons and clicking on them)
def test_MyDevices(self):
browser.find_element_by_xpath('Some XPATH').click()
if __name__ == '__main__':
unittest.main()
And here is my problem after performing test_LoginIn I want to start another test test_MyDevices because MyDevice tab is right after logging in on the same page as first test is ended, but I can't because next test want to create new Web Driver Instance instead of doing test in the same instance.
In current version I receive this error:
Error after running script
I read a lot about this issue but couldn't find any satisfactory answer.
I'd be grateful for your help.

You can use the same instance of the webdriver for all of your tests. You will just need to instantiate the webdriver once, and then use it throughout your tests.

Related

Interaction with whatsapp web using python

Is it possible to make a program in python in which the program will look for a message on WhatsApp sent by a particular person on a group(which I have pinned for convenience) at a particular time and then it will print the message sent by that person?
Well if you don't understand my question let me give you an example:
Suppose there is a group named ABCD which is pinned on WhatsApp web(which means it is at the top)
It consists of 4 people - A,B,C,D
I want the program to print the message sent by C at time 13:05 in that group
Is this thing possible on python?
I can use any module like selenium or even pyautogui
Yes, it is possible through Selenium without using any kind of API.
First we will import required modules:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time
Now we will launch Whatsapp Web:
driver = webdriver.Chrome()
driver.get("https://web.whatsapp.com")
You can use other browsers, for this example we will be using Chrome.
Now we will locate the Search or Start New Chat button using XPath and add a webdriver wait for it:
search_button = WebDriverWait(driver,50).until(lambda driver: driver.find_element_by_xpath("//input[#title='Search or start new chat']"))
Now we will click it and add a little sleep:
search_button.click()
time.sleep(2)
Now we will Send the name of the Person to contact into the text area:
search_button.send_keys("A")
time.sleep(2)
Now we will send a message
input_box = driver.find_element_by_xpath(r'//div[#class="_2S1VP copyable-text selectable-text"][#contenteditable="true"][#data-tab="1"]')
time.sleep(2)
input_box.send_keys("Hello" + Keys.ENTER)
time.sleep(2)
You can using Chrome inspect more and do more things.

How to fill a textfield and pressing a button multiple times in order in Selenium?

I want to automatically fill out a form and then click the Subscribe button multiple times on this certain website. But somehow the behaviors are inconsistent and the actions aren't performed in a correct order.
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome("chromedriver.exe")
browser.get("https://www.facen.co/")
emails = ["mikhail67#gmail.com", "konovalov878#gmail.com", "miruki451#gmail.com"]
# send a list of random emails
for email in emails:
sub_textfield = browser.find_element_by_id("comp-ka58ijvyinput")
sub_button = browser.find_element_by_id("comp-ka58ijw9link")
ActionChains(browser).move_to_element(sub_textfield).send_keys(email).move_to_element(sub_button).click().perform()
I tried to keep order of executions using ActionChains, but it doesn't seem to be working. What could be the problem?
Try adding some delays using the time module
and also DO NOT execute the last line as a whole thing in a single line
use name spacing and put them in different lines and add some delays so this will give the computer some time to know whats happening and let the thing load
That could be the problem sometimes that the code has run faster than the page has loaded
Typically something like this would not need to use ActionChains. It doesn't sound like you have a timing issue but I would add a wait to the first line in your loop just to be safe.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome("chromedriver.exe")
browser.get("https://www.facen.co/")
emails = ["mikhail67#gmail.com", "konovalov878#gmail.com", "miruki451#gmail.com"]
# send a list of random emails
for email in emails:
WebDriverWait(browser, 10).until(EC.visibility_of_element_located((By.ID, "comp-ka58ijvyinput")).send_keys(email)
browser.find_element_by_id("comp-ka58ijw9link").click()

Selenium web driver native functions work but same functions of ActionChains class do not on the same element

While trying to automate using Selenium webdriver and python I am facing the following issue:
Simple click is working without action chains class:
element.click()
But trying to click is not working using action chains class:
from selenium.webdriver.common.action_chains import ActionChains
action = ActionChains(driver)
action.click(element).perform()
Similarly, trying to drag drop not working using action chains class:
action.drag_and_drop_by_offset(element,0,100).perform()
action.drag_and_drop(element,element2).perform()
Using ActionChains gives a stale element exception.
Is there any other way to perform these operations like move_to, mouse_press, mouse_release, drag_drop etc. without ActionChains class
Further - working directly with driver commands:
from selenium.webdriver.remote.command import Command
driver.execute(Command.CLICK_ELEMENT, {"id":getattr(element,"id")})
But this does not:
from selenium.webdriver.remote.command import Command
driver.execute(Command.MOVE_TO, {"id":getattr(element,"id")})
driver.execute(Command.MOUSE_DOWN, {})
driver.execute(Command.MOVE_TO, {"id":getattr(element2,"id")})
driver.execute(Command.MOUSE_UP, {})
Also, observed that the jquery to retrieve the position of the object returns undefined even though the object is present:
$($x('div[draggable="true" and #class="result selected-row"][1]')).position()
Any suggestions?

Reopen same browser window using selenium python and Firefox

Hey i'm trying to make an automatic program to send Whatsapp messages.
I'm currently using python, Firefox and selenium to achieve that.
The problem is that every time i'm calling driver.get(url) it opens a new instance of the firefox browser, blank with no memories of the last run. It makes me scan the bar code every time I run it.
from selenium import webdriver
from selenium.webdriver.firefox.webdriver import FirefoxProfile
cp_profile = webdriver.FirefoxProfile("/Users/Hodai/AppData/Roaming/Mozilla/Firefox/Profiles/v27qat5d.whatsapp_profile")
driver = webdriver.Firefox(executable_path="/Users/Hodai/Desktop/geckodriver",firefox_profile=cp_profile)
driver.get('http://web.whatsapp.com')
#Scan the code before proceeding further
input('Enter anything after scanning QR code')
I've tried to use profile but it seems like it has no affect.
cp_profile = webdriver.FirefoxProfile("/Users/Hodai/AppData/Roaming/Mozilla/Firefox/Profiles/v27qat5d.whatsapp_profile")
driver = webdriver.Firefox(executable_path="/Users/Hodai/Desktop/geckodriver",firefox_profile=cp_profile)
At the end I used chromedriver to achive my goal.
I tried cookies with pickle but it was a bit tricky because it remembered the cookies just for the same domain.
So I used user data for chrome.
now it works like a charm. thank you all.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("user-data-dir=C:/Users/Designer1/AppData/Local/Google/Chrome/User Data/Profile 1")
driver = webdriver.Chrome(chrome_options=options,executable_path="C:\webdrivers\chromedriver.exe")
The easiest way I think is to save your cookies after scanned the qrcode and push them to Selenium manually.
# Load page to be able to set cookies
driver.get('http://web.whatsapp.com')
# Set saved cookies
cookies = {'name1': 'value1', 'name2', 'value2'}
for name in cookies:
driver.add_cookie({
'name': name,
'value': cookies[name],
})
# Load page using cookies
driver.get('http://web.whatsapp.com')
To get your cookies you can use the console (F12), Network tab, right click on the request, Copy => Copy Request Headers.
It should not be like that. It only opens the new window when initialized with new variable or the program starts again. Here is the code for chrome. It doesn't matter how many times you call driver.get(url) it would open the url in the same browser window
from selenium import webdriver
import selenium.webdriver.support.ui as ui
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
import time
driver = webdriver.Chrome(executable_path=r"C:\new\chromedriver.exe")
driver.get('https://www.olx.com.pk/lahore/apple/q-iphone-6s/?search%5Bfilter_float_price%3Afrom%5D=40000&search%5Bfilter_float_price%3Ato%5D=55000')
time.sleep(10)
driver.get('https://www.olx.com.pk/lahore/apple/q-iphone-6s/?search%5Bfilter_float_price%3Afrom%5D=40000&search%5Bfilter_float_price%3Ato%5D=55000')
time.sleep(10)
driver.get('https://www.olx.com.pk/lahore/apple/q-iphone-6s/?search%5Bfilter_float_price%3Afrom%5D=40000&search%5Bfilter_float_price%3Ato%5D=55000')
time.sleep(10)
Let me know if the issue is resolved or you are trying to do something else.

Selenium Webdriver: How to take full page screenshot using FireShot written in Python

In Selenium Webdriver, I am looking to be able to take a full page screenshot using FireShot executed from a Python script.
I have the following code so far:
import unittest
import execjs
from execjs import get
from selenium import webdriver
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.keys import Keys
class PythonOrgSearc(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome('/usr/bin/chromedriver');
def test_login_and_make_payment_on_account(self):
driver = self.driver;
driver.set_window_size(1024,768);
# Log in to My Account
driver.get("https://www.mywebsite.com");
self.assertIn("Sign In", driver.title);
driver.save_screenshot('/Users/username/Documents/Selenium_Test/01a_login.png');
# Enter username
user = driver.find_element_by_id("EmailOrAccountNumber");
user.send_keys("user#me.co.uk");
# Enter password and submit form
password = driver.find_element_by_id("Password");
password.send_keys("password123");
driver.save_screenshot('/Users/username/Documents/Selenium_Test/01b_login_filled.png');
password.send_keys(Keys.RETURN);
# Confirm logged into My Account
self.assertIn("Account Summary", driver.title);
driver.save_screenshot('/Users/username/Documents/Selenium_Test/02a_My_Account.png');
def tearDown(self):
self.driver.close();
if __name__ == "__main__":
unittest.main();
I have installed PyExecJS, but have no idea how I can begin using the FireShot API to replace the current save_screenshot functions used in the code. Thank you for any steer or guidance you can provide.
I think it is better to use driver.execute_script command to execute your javascript in the browser, but if you want to check a markup, perhaps, applitools could help you

Categories