Why im not able to use executeScript in my selenium script? - selenium

import org.openqa.selenium.*;
import org.openqa.selenium.JavascriptExecutor.executeScript;

You don't need executeScript in your import:
import org.openqa.selenium.JavascriptExecutor;

Related

Automatically Scroll a Non-Active Selenium Based Browser Window

I need a way to automatically scroll a browser window that i've opened using selenium code. I am currently using pyautogui but this requires the window to be selected. This is running on a virtual machine that i'm remoting into and when i toggle off the VM to work on my main desktop the code does not scroll so i need a way to auto scroll on a non active window.
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
import numpy as np
from pynput.mouse import Button, Controller
import win32api
import win32con
import pyautogui
import pandas as pd
import re
from selenium.common.exceptions import TimeoutException
pyautogui.FAILSAFE = False
s = Service(r'\\homedirpva1a01\USERSNC$\603225\Edgedriver\msedgedriver.exe')
browser = webdriver.Edge(service=s)
Options.page_load_strategy = 'eager'
time.sleep(5)
linklist=[]
browser.get('https://turo.com/us/en/search?country=US&defaultZoomLevel=11&delivery=false&deliveryLocationType=googlePlace&endDate=01%2F25%2F2023&endTime=10%3A00&isMapSearch=false&itemsPerPage=200&latitude=40.735657&location=Newark%2C%20New%20Jersey%2C%20USA&locationType=CITY&longitude=-74.1723667&pickupType=ALL&placeId=ChIJHQ6aMnBTwokRc-T-3CrcvOE&region=NJ&sortType=RELEVANCE&startDate=01%2F22%2F2023&startTime=10%3A00&useDefaultMaximumDistance=true')
time.sleep(3)
print('start4434')
i4434=1
elems4434=[]
while i4434<50:
if 'An error occurred while searching, please try again' in browser.page_source:
listsave=['i4434','i4434']
save = pd.DataFrame(listsave)
save.to_csv(r'\\PATH\savetest.csv')
exit()
elif 'vehicle-card-link-box' not in browser.page_source:
listsave=['i4434','i4434']
save = pd.DataFrame(listsave)
save.to_csv(r'\\PATH\savetest.csv')
break
else:
elems4434=browser.find_elements(By.XPATH, '//a[#href]')
distinctlist = list(set(linklist))
frame = pd.DataFrame(distinctlist)
frame.to_csv(r'\\PATH\turolinklisttest.csv')
listsave=['i4434','i4434']
save = pd.DataFrame(listsave)
save.to_csv(r'\\PATH\savetest.csv')
for elem in elems4434:
if 'car-rental/united-states' in elem.get_attribute('href'):
linklist.append(elem.get_attribute('href'))
if 'suv-rental/united-states' in elem.get_attribute('href'):
linklist.append(elem.get_attribute('href'))
pyautogui.scroll(-1000)
time.sleep(3)
i4434+=1`

AttributeError: 'element_to_be_clickable' object has no attribute 'click' python3.7

As my code shows, I am trying to automate the process of logging and other things using selenium in python 3.7. I am struck as it is showing "AttributeError: element_to_be_clickable has no object click" in the line botton_to_click().
from bs4 import BeautifulSoup
from bs4.element import Tag
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
base = 'https://www.wsj.com'
url = 'https://www.wsj.com/search/term.html?KEYWORDS=cybersecurity&min-date=2018/04/01&max-date=2019/03/31&isAdvanced=true&daysback=90d&andor=AND&sort=date-desc&source=wsjarticle,wsjpro&page=1'
browser = webdriver.Safari(executable_path='/usr/bin/safaridriver')
browser.get(url)
browser.find_element_by_id('editions-select').click()
browser.find_element_by_id('na,us').click()
botton_to_click = WebDriverWait(browser, 10).until(EC.element_to_be_clickable, ((By.XPATH,"//button[#type='button' and contains(.,'Sign In')]")))
botton_to_click.click()
browser.find_element_by_id('username').send_keys('##$%*&^%##$')
browser.find_element_by_id('password').send_keys('##*$%^!#')
browser.find_element_by_id('basic-login').click()
browser.find_element_by_id('masthead-container').click()
browser.find_element_by_id('searchInput').send_keys('cybersecurity')
browser.find_element_by_name('ADVANCED SEARCH').click()
browser.find_element_by_id('dp1560924131783').send_keys('2018/04/01')
browser.find_element_by_id('dp1560924131784').send_keys('2019/03/31')
browser.find_element_by_id('wsjblogs').click()
browser.find_element_by_id('wsjvideo').click()
browser.find_element_by_id('interactivemedia').click()
browser.find_element_by_id('sitesearch').click()
browser.close()
Thanks.
Remove the comma after element_to_be_clickable as given below, It may resolve your issue.
botton_to_click = WebDriverWait(browser, 10).until(EC.element_to_be_clickable, ((By.XPATH,"//button[#type='button' and contains(.,'Sign In')]")))
to
botton_to_click = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,"//button[#type='button' and contains(.,'Sign In')]")))

Click button doesn't work - Katalon Studio

I am new to Katalon studio and am trying to run my test case but it's always filed as it says:
Error:
Test Cases/Logging in FAILED because (of) (Stack trace: com.kms.katalon.core.exception.StepFailedException: Unable to >click on object 'Object Repository/Page_BaseLine - test/input_Przypomnienie o fakturze' (Root cause: com.kms.katalon.core.webui.exception.WebElementNotFoundException: Web element with id: 'Object Repository/Page_BaseLine - test/input_Przypomnienie o fakturze' located by 'By.xpath: >//input[#id='SubmitButton']' not found)
I tried to do it manually but everytime the same problem appears, what shall I do then?
Here is my source code:
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.checkpoint.CheckpointFactory as CheckpointFactory
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as MobileBuiltInKeywords
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testcase.TestCaseFactory as TestCaseFactory
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testdata.TestDataFactory as TestDataFactory
import com.kms.katalon.core.testobject.ObjectRepository as ObjectRepository
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WSBuiltInKeywords
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUiBuiltInKeywords
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
import org.openqa.selenium.Keys as Keys
import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW
WebUI.openBrowser('')
def plik = new File('Config.txt')
def lines = plik.readLines()
WebUI.navigateToUrl(lines[0])
WebUI.setText(findTestObject('Object Repository/Page_Demo version BaseLine/input_Login form_LoginTextBox'), lines[1])
WebUI.setText(findTestObject('Object Repository/Page_Demo version BaseLine/input_Login form_PasswordTextB'), lines[2])
WebUI.click(findTestObject('Object Repository/Page_Demo version BaseLine/input_remember me_LoginButton'))
WebUI.click(findTestObject('Page_BaseLine - test/a_Kontrahenci'))
WebUI.click(findTestObject('Page_BaseLine - test/a_Dodaj Kontrahenta'))
WebUI.setText(findTestObject('own/Page_BaseLine - test/input_Nazwa skrcona_ShortNameT'), 'greg12')
WebUI.setText(findTestObject('own/Page_BaseLine - test/textarea_'), 'Grzegorz Spytek12')
WebUI.click(findTestObject('Page_BaseLine - test/input_Przypomnienie o fakturze'))
WebUI.click(findTestObject('Page_BaseLine - test/input_Opis_CloseButton'))
Thanks for help.
The xpath seems not correct. Could you try removing the '>'?
>//input[#id='SubmitButton']'

Selenium is not calling the website

I'm trying selenium for the first time. My code is as follows:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
import selenium.webdriver.support.ui as ui
import selenium.webdriver.support.expected_conditions as EC
import os
import time
class expediaUnitTest():
def __init__(self):
options = webdriver.ChromeOptions()
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
dir_path=os.getcwd()
chromedriver=dir_path+"\chromedriver"
os.environ["webdriver.chrome.driver"]=chromedriver
driver=webdriver.Chrome(chrome_options=options,executable_path=chromedriver)
def timerPractice(self):
time.sleep(5)
def gotoexpedia(self):
self.driver.get("https://www.expedia.com/")
def teardown(self):
self.driver.close()
if __name__=="__main__":
obj=expediaUnitTest()
obj.gotoexpedia()
A new chromebrowser is called but it does not access the webpage. I get the errormessage:
AttributeError: 'expediaUnitTest' object has no attribute 'driver'
When i give the timePractise(), it works perfectly,as in the browser disappears after the given number of seconds. But it does not seem to be calling a function.
Ps: I'm following the online tutorial given here:https://www.youtube.com/watch?v=zZjucAn_JYk
He doesn't have the problem that I'm having.
Can someone please help?
You are missing self when creating the instance of the driver. So instead of
driver=webdriver.Chrome(chrome_options=options,executable_path=chromedriver)
it should be
self.driver=webdriver.Chrome(chrome_options=options,executable_path=chromedriver)
(in the video they are doing it exactly that way)

How to run Jmeter webdriver sampler file uploading script in blazemeter?

I have a Jmeter webdriver sampler script it is running fine in Jmeter. Now I want it to run on blazemeter. Since I was using local directory in Jmeter it was fine. But I am not able to upload file using any path. Can some body help on this. I need to upload file in blazemeter using jmeter webdriver sampler. What path Can I give and where should I keep my file?
Also I tried my file keeping in shared folders of Blazemeter. but I failed in that. Please some body give some syntax for it.
import org.apache.jmeter.services.FileServer;
import org.openqa.selenium;
import java.awt.Robot;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import org.openqa.selenium.firefox.FirefoxProfile;
import java.time.temporal.ChronoUnit;
import java.time.format.DateTimeFormatter;
import java.time.LocalDateTime;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileWriter;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import org.testng.asserts.SoftAssert;
import java.util.List;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
WebDriverWait wait= new WebDriverWait(WDS.browser,20);
WDS.sampleResult.sampleStart();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[#class='menu-main']/child::li"))).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//p[#class='btn btn-outline']"))).click();
WDS.log.info("Dialog box");
Robot robot= new Robot();
robot.setAutoDelay(2000);
filepath="home/jmeter/Deepak/ColumnFunctionFile.csv";
StringSelection stringselection = new StringSelection(filepath);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringselection, null);
robot.setAutoDelay(1000);
WDS.log.info("Copy");
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
WDS.log.info("release");
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_V);
WDS.log.info("enter press release");
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
robot.setAutoDelay(2000);
//upload file status
WebDriverWait wait2= new WebDriverWait(WDS.browser,5);
oldTimeForProgress=LocalDateTime.now();
try{
wait2.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[#class='progress progress-mini']")));
WDS.log.info("--------------------------------Progress bar gets invisible now-------------------");
}
catch(Exception e)
{
WDS.log.info("---------------Looking like file got stuck in processing messages----------------");
}
As far as I can see from the Selenium Webdriver Based Testing article you should just upload your .jmx script and BlazeMeter will pick it up. Just make sure not to use Internet Explorer as their systems seem to be running on Linux so only Firefox and Chrome are supported.
Also my expectation is that you should reach out to BlazeMeter Support in case of any issues, they should be more aware of their infrastructure than anyone here.