A loop for refreshing page that stop when a button/xpath is clickable - selenium

trying to create a loop that refreshes the page continuously until button or xpath becomes available then it will break (dont bully my poor coding i'm new)
if Date == '1':
bool (buttonActive) == False;
list <WebElement> element = driver.find_element_by_xpath('//*[#id="booking-slots-slider"]/div[1]/button')
while (buttonActive):
if (element.size() > 0):
buttonActive = True;
element.get(0).click();
else:
driver.refresh()
List<WebElement> add = driver.find_element_by_xpath('//*[#id="booking-slots-slider"]/div[1]/button')

Related

How can I wait for an animation to be finished without using a sleep in selenium using perl?

I have observed that when I fill a form with selectboxes it does not fill up correclty (it seems like sometimes the option is not selected) if I fill all parameters without a sleep between the click to open the select box and the click to select an option.
If I have a sleep between the first click and the second it seems to work properly, but if I have a big set of select boxes filling the forms slows down a lot.
Is there a way to do this in some kind of "wait for an animation to be finished"? This is the code I'm using simplified:
use strict;
use warnings;
use Selenium::Chrome;
use Selenium::Waiter qw/wait_until/;
my $chrome_driver_path = "chromedriver.exe";
my $driver;
my %settings = (
'binary' => $chrome_driver_path,
);
$driver = Selenium::Chrome->new(%settings);
$driver->get("http://mywebiste.com/myform_with_selectbox");
_set_select_box($driver, "myoption");
sub _set_select_box{
my ($driver, $input) = #_;
# Open selectbox
my $element_id = 'some_label';
my $element;
wait_until{ $element = ($driver->find_elements("//label[\#id='$element_id']"))[0] };
if (defined($element)){
$log->debug("element_id: '$element_id' found");
}else{
$log->error("element_id: '$element_id' could not be found");
return -1;
}
wait_until{$element->click()};
$log->debug("element_id '$element_id' clicked");
# sleep(1); here I put a sleep and it seems to work always
# Click item in selectbox
my $element_2_id = 'some_items';
my #elements;
wait_until{ #elements = ($driver->find_elements("//ul[\#id='$element_2_id']//li")) };
if (defined($elements[0])){
$log->debug("element_2_id: '$element_2_id' found");
}else{
$log->error("element_2_id: '$element_2_id' could not be found");
return -1;
}
my $selectbox_text = $config->val( 'MyOptions', $input);
return -1 if (!defined($selectbox_text));
foreach my $element_2 (#elements){
my $option_text = $element_2->get_text();
$option_text = encode('UTF-8', $option_text, Encode::FB_CROAK) if (defined($option_text)); # otherwise selenium does not return utf8
if ($option_text eq $selectbox_text){
$log->debug("selectbox_text '$selectbox_text' found");
wait_until{$element_2->click()};
$log->debug("selectbox_text '$selectbox_text' clicked");
return 1;
}else{
$log->debug("Selectbox text does not match Found: '$option_text' Expected '$selectbox_text'");
}
}
return 0;
}

Selenium Bot: Irregular Switching of Windows

Once I'm clicking the element More Information, the link is getting clicked and then the window is jumping back to it's previous window and a TimeoutException is being shown.
Code:
self.driver.window_handles
base = "https://outlook.office.com/mail/inbox/id/AAQkADQ0ZmY1YmRkLWExNDEtNGNlYS1iOTZmLTVmNzNjMzhkNjUyMgAQAJmE%2FyrhD0supMphUUSGrmQ%3D"
window_set = {self.driver.window_handles[0], self.driver.window_handles[1]}
for x in window_set:
if(base != x):
self.driver.maximize_window()
wait = WebDriverWait(self.driver, 10)
self.driver.switch_to.window(x)
frame = wait.until(EC.presence_of_element_located((By.NAME, "mainFrame")))
self.driver.switch_to.frame(frame)
element = wait.until(EC.element_to_be_clickable((By.ID, "mc-lnk-moreInfo")))
element.click()
Please HELP!
WebPage Image:(contains both the tabs)
In this image More Information has been clicked and has changed to Less Information
This did the job!
self.driver.window_handles
wait = WebDriverWait(self.driver, 10)
base = self.driver.window_handles[0]
child = self.driver.window_handles[1]
windows = {self.driver.window_handles[0], self.driver.window_handles[1]}
for x in windows:
if(base != x):
self.driver.switch_to.window(x)
frame = wait.until(EC.presence_of_element_located((By.NAME, "mainFrame")))
self.driver.switch_to.frame(frame)
element = wait.until(EC.element_to_be_clickable((By.ID, "mc-lnk-moreInfo")))
element.click()

All the links in the same row

I'm doing a database where it has 2 columns: event_name and event_URL. It doesn't get the name and puts all the urls on the event_URL column. Print: https://prnt.sc/fru1tr
Code:
import urllib2
from bs4 import BeautifulSoup
import psycopg2
page = urllib2.urlopen('https://www.meetup.com/find/outdoors-adventure/?allMeetups=false&radius=50&userFreeform=London%2C+&mcId=c1012717&change=yes&sort=default')
soup = BeautifulSoup(page, 'lxml')
events = soup.find('ul', class_='j-groupCard-list searchResults tileGrid tileGrid--3col tileGrid_atMedium--2col tileGrid_atSmall--1col')
A = []
B = []
try:
conn = psycopg2.connect("dbname='meetup' user='postgres' host='localhost' password='root'")
except:
print 'Unable to connect to the database.'
cur = conn.cursor()
for event in events.findAll('li'):
text = event.findAll('h3')
if len(text) != 0:
A.append(text[0].find(text = True))
url = event.find('a', href=True)
if len(url) != 0:
B.append(url['href'])
cur.execute("""INSERT INTO outdoors_adventure(event_name,event_url) VALUES(%s,%s)""", (tuple(A),tuple(B)))
conn.commit()
del A[:]
del B[:]
If the indentation is right in the posted code, the problem might be in the nested for-loop: for every event, you append the "B" list with all the links on the page. You could try:
for event in events.findAll('li'):
text = event.findAll('h3')
if len(text) != 0:
A.append(text[0].find(text = True))
for link in events.findAll('li'):
url = link.find('a', href=True)
if len(url) != 0:
B.append(url['href'])
Or better, keep the event-name and event-URL search in a single for-loop, fetching first the text and then the url of event
EDIT: You can simplify the name extraction, by using:
for event in events.findAll('li'):
text = event.h3.string.strip()
if len(text) != 0:
A.append(text)
url = event.find('a', href=True)
...
Let me know if that does the trick for you (it does on my side).
EDIT2: The problem might be just the fact that the extracted string starts with tabs (maybe that's why your DB seems "not to show the name" - its there, but you only see the tabs in the preview?). Just use strip() to remove them.

How to handle Mouseover in Selenium 2 API

String strPrimaryNav = "MEN";
String strSecondaryNav = "Shoes";
String strTertiaryNav = "Golf";
driver.findElement(By.linkText(strPrimaryNav)).click();
WebElement weSecNav = driver.findElement(By.className("secondaryButton").linkText(strSecondaryNav));
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseDown(((Locatable)weSecNav).getCoordinates());
//just trying with for loop as the tertiary popup disappears quickly and hence getting ElementNotVisible Exception
for (int i = 0 ; i< 2; i++){
mouse.mouseDown(((Locatable)weSecNav).getCoordinates());
//mouse.mouseMove(((Locatable)weSecNav).getCoordinates(), 0, 0 );
//WebElement weTerNav = driver.findElement(By.className("tertiaryButton").linkText(strTertiaryNav));
WebElement weTerNav = driver.findElement(By.linkText(strTertiaryNav));
boolean isSecDisplayed = ((RenderedWebElement)weTerNav).isDisplayed();
System.out.println("isDisplayed: " + isSecDisplayed);
System.out.println(" " + ((RenderedWebElement)weSecNav).getAttribute("href"));
System.out.println(" " + ((RenderedWebElement)weSecNav).getValueOfCssProperty("action"));
weTerNav.click();
}
I was trying the below code using selenium 2 but, the tertiary popup not stays long to click it and hence getting ElementNotVisible exception at Tertiary click.
You can at least check that the element is visible before you send your click:
Selenium s = new WebDriverBackedSelenium( driver, URL );
s.waitForCondition( "!( document.getElementById('.....') === null )", "20000" );
s.click( .... );
This avoids the exception. I'm not sure there is a way to make the popup stay any longer than it should.

Adobe 9 Check box required field

I've created reports in Adboe that have checkobxes and set then to required fields.
But when i click the submit button all fields but the check boxes are validated.
I.e
If i dont complete the required textbox field the report will not submit, but when i do and the required checkbox fields are not checked it still submits.
This only appears to be happening on Adobe 9
Any ideas?
Thanks
Sp
Here is a link to a test page
http://www.mediafire.com/?mnkmmlime2f
If you fill the text box with anything it will submit regardless of the check box status (which is also a required field)
I have figured it out.
Adobe Reader checkbox allows has a value (default "false") so when the form validates it sees the checkbox as having a value.
I've had to write some java to stop the form submitting if the checkbox has a null/False/false value
This works like a dream
Thanks for trying to help wit hthis post all
var f;
var Valid = "1";
for (var i = 0; i < this.numFields; i++)
{
f = this.getField(this.getNthFieldName(i));
if (f.type == 'checkbox')
{
if(f.required == true)
{
if(f.value == "false" || f.value == "False" || f.value == "null")
{
Valid = "0";
}
}
}
};
if(Valid == "1")
{
this.submitForm('');
}
else
{
app.alert("Please complete all required fields");
}