How to accept span button using Selenium? - selenium

I'm trying to accept cookies with Selenium, but the accept button is not found. I am not familiar with Selenium and I don't know how to debug. For instance, if I try to accept cookies from webrankinfo.com.
This is my code:
driver = webdriver.Chrome("chromedriver")
driver.get("https://www.webrankinfo.com")
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[normalize-space()='Tout accepter et continuer']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(., 'Tout accepter et continuer')]"))).click()
Whatever the selected option (Xpath or CSS), the button is not found. What is the solution?
Moreover, is there any option to debug Xpath directly on my Web Browser like Chrome or Firefox?
EDIT :
Because most people can't see the cookie banner, I share the original cookie framework used. I think you can't see banner because it's not obligated when you're not in Europe.
You can force banners to appear by going to https://www.consentframework.com/#/ and clicking on Gérer vos préférences (green button) on top right.

I can help you using a CSS selector, I've managed to locate the element and here's what you can utilise:
#sd-cmp .sd-cmp-3V2Vm span.sd-cmp-3cRQ2
#sd-cmp is the unique ID for the cookie banner
.sd-cmp-3V2Vm is a row class containing the Accept all/do not accept/Set your choices buttons. I've used this because it seems you have an older version of this row class (sd-cmp-25TOo) containing the exact same button locators in the DOM but are no longer visible on the UI - this is likely the cause of the problems as it's finding these hidden ones first
span.sd-cmp-3cRQ2 is specifically the Accept all button
Screenshot - Accept All selected

I see no any "accept cookies" button appearing on that web page, so I can't help with providing locator for it.
As about debugging the locators with Chrome of Firefox:
You can press F12 on your browser, it will open the Developer Tools.
Then select Elements tab there.
Then you can locate any element with the arrow in the upper-left corner there.
It will present all the attributes of the selected element.
Control+F on that view will allow you to search elements on that page with XPath or CSS Selector.
See also here or any other resource about locating web elements with Developer Tools.

As Prophet, no cookie alert appears for me, so I can't help you locate the button. Although, I can help you trying to make the cookie alert not appear at all.
Some websites will only require cookies for certain browsers or browser versions. This way, changing the user agent of the WebDriver may cause the alert to disappear. Your code would be like this:
options = webdriver.ChromeOptions()
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
options.add_argument('user-agent={0}'.format(user_agent))
driver = webdriver.Chrome("chromedriver")
driver.get("https://www.webrankinfo.com")
That user agent is just an example, maybe it won't work but others will. You're able to find older versions of Chrome here.
What may be happening, also, is that the website is detecting an automate tool. It would explain why the cookie alert doesn't show up for us. To prevent the detection, you'll have to add some option arguments to WebDriver:
options = webdriver.ChromeOptions()
options.add_argument('--no-sandbox')
options.add_argument('--allow-running-insecure-content')
options.add_argument('--ignore-certificate-errors')
options.add_argument('-allow-insecure-localhost')
options.add_argument('--remote-debugging-port=9222')
options.add_argument('--disable-gpu')
options.add_argument('--start-maximized')
options.add_experimental_option("useAutomationExtension", False)
options.add_experimental_option("excludeSwitches",["enable-automation"])
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'
options.add_argument('user-agent={0}'.format(user_agent))
driver = webdriver.Chrome("chromedriver")
driver.get("https://www.webrankinfo.com")
Some of these arguments may be useless. So you can test them one by one and let on your code only the usefull ones.

As I seen the cookie info thing loads later than the page it self so use wait before the actual click on the accept button.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.elementClickable( insert your element here ));
Then another suggestion for the xpath, if you want to find a span by the text inside it
//span[text()='Accept all']
and I think the correct form for your second attempt would be
//span[text()[contains(.,'Accept all')]]

Related

How to scroll in selenium headless mode using Java?

Description
Because I don't yet have got any answer from mine post:
How to get all stocks from the specified URL in selenium headless mode?
I have to work on workaround to get progress on my work! Instead of trying to force an update on the site to get all stocks viewable (as described in my post) I will go to the end of page and then scroll up to force all stocks to get viewable (works fine when I do it manually).
All this MUST work in selenium headless mode!
Problem
I know how this can be implemented in selenium normal mode (not headless) but I can't get it to work in headless mode.
I think this line works both in normal and headless mode to go to the END of page:
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
The issue I'm struggeling with is how to scroll up or pageup from the end of the page. I guess something like this will work:
WebElement e = driver.findElement(By.xpath("element to be returned like Storskogen"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();", e);
I can't fetch the element "e", I can't get it work (NoSuchElementException is thrown). I have copied the xpath or css from Chrome without result though. I'm not even sure this will work in headless mode.
Questions
how to fetch element "Storskogen"?
is "scrollIntoView" scrolling working in headless mode?
how can pageup be implemented and working in headless mode?
how can I verify scrolling in headless mode?
It's okay to not answer every question. I use Java for implemention.
Selenium headless window/display size by default is 800x600.
So if you have a lot on your webpage, then you may end up with horizontal, as well as vertical scroll bars on the headless browser. Therefore, dependent on your webpage, the element you are after may not be drawn, hence you have to scroll up and down for it to appear.
To get the best results of scrolling up and down, you want to maximise your browser window. As you want to operate in headless mode, the actual browser will not be active, thus driver.manage().window().maximize(); is not an option.
Do the following:
Update your browser driver with a specific window size that will ensure no horizontal scroll bars. I have used the following for my BrowserDriverFactory as I test with multiple browsers: driver.manage().window().setSize(new Dimension(1920, 1280)); also you could manage a specific browser driver i.e. chromedriver with options.addArguments("window-size=1920,1080");
Then use JavascriptExecutor, as you mentioned above:
Scroll down - ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
Scroll up - ((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollTop);");

Not able to locate web element on chrome browser's settings popup

I am trying to clear browser cache, for which i need to click on clear data button of browser setting popup, but, i am not able to write xpath for the button on chrome browser
i have tried inspecting the element to find out if the button is on a iframe but its not in iframe, so i have decided to try it with an with out iframe snippet, either of ways the element is not traces out in dom
public void clearBrowserCache() throws InterruptedException{
driver.get("chrome://settings/clearBrowserData");
Thread.sleep(2000);
System.out.println(driver.getWindowHandles());
String windowIds=driver.getWindowHandle();
// driver.switchTo().frame(windowIds);
driver.findElement(By.cssSelector(
[id=clearBrowsingDataConfirm]")).click();
}
Expected is that i should be able to click on the clear data button
Actual is that i am not able to find out the xpath for of the emlement
Depending on which version of chrome you are using, this could work:
driver.findElement(By.cssSelector("* /deep/ #clearBrowsingDataConfirm")).click();
However the /deep/ combinator is deprecated, so it may not work on newer Chrome's versions.
I answered how to reach inside the Shadow DOM in an other question.
You can read the whole thing at the link, but the basics are you create a "starting point" WebElement at the Shadow DOM via JavaScript, then all future look-ups reference it:
WebElement button = startingPoint.findElement(By.cssSelector("..."));

How to resolve org.openqa.selenium.WebDriverException?

I am writing an automated test and want to report bugs, if occur, directly in the repo at GitHub. The step which fails in my program is the Submit new issue button from GitHub Issue Tracker.
Here is the code:
WebElement sendIssue = driver.findElement(By.xpath("/html/body/div[5]/div/div/div[2]/div[1]/div/form/div[2]/div[1]/div/div/div[3]/button"));
sendIssue.click();
And the exception:
org.openqa.selenium.WebDriverException: Element is not clickable at
point (883, 547.7999877929688). Other element would receive the click:
div class="modal-backdrop"></div
The following command also does not work:
((JavascriptExecutor) driver).executeScript("arguments[0].click();", sendIssue);
How can I make it clickable? Is there any other way by which I can resolve this issue?
This is happening because when selenium is trying to click ,the desired element is not clickable.
You have to make sure that the Xpath provided by you is absolutely right.If you are sure about the Xpath then try the following
replace
WebElement sendIssue = driver.findElement(By.xpath("/html/body/div[5]/div/div/div[2]/div[1]/div/form/div[2]/div[1]/div/div/div[3]/button"));
sendIssue.click();
with
WebElement sendIssue =(WebElement)new WebDriverWait(DRIVER,10).until(ExpectedConditions.elementToBeClickable(By.xpath("/html/body/div[5]/div/div/div[2]/div[1]/div/form/div[2]/div[1]/div/div/div[3]/button")));
sendIssue.click();
If that doesn't work ,You will get an Timeout exception, In that case try incaresing the timeout amount from 10 to 20.
If it still doesn't work please post a screenshot of the HTML.
You need to write something in the issue title and description to make the issue clickable are you sure you are not making that mistake of clicking the button without writing anything in those places I am adding screenshot for your convenience.
Selenium Webdriver introduced in a previous version (v2.48) a new behavior that prevent clicks on elements that may be overlapped for something else (a fixed header or footer - for example) or may not be at your viewport (visible area of the webpage within the browser window).
You can see the debate here.
To solve this you will need to scroll (up or down) to the element you're trying to click.
One approach would be something like this post:
Page scroll up or down in Selenium WebDriver (Selenium 2) using java
Another, and maybe more reasonable, way to create a issue on Github, would be using their API. Maybe it would be good to check out!
Github API - Issues
Gook luck.
This worked for me. Instead of HTML browser this would be useful if we perform intended Web Browser
// Init chromedriver
String chromeDriverPath = "/Path/To/Chromedriver" ;
System.setProperty("webdriver.chrome.driver", chromeDriverPath);
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200","--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);

Unable to click button in mobile web in appium

After exhaustively searching for this over various forums, I still don't have an answer.
Here are complete details
I'm identifying the element through classname which points to multiple(4) buttons. I'm iterating through buttons and then search for text and when there is a match i click it.
This works fine with selenium webdriver and browsers such as firefox,chrome
Now I'm doing the same thing with appium.
Out of 4 buttons which are identified through classname, the script clicks 2 buttons successfully but for two buttons click happens(i can see the button being clicked) but new page which should be loaded is not loaded. The buttons for which click is not happening are in a footer class and other two are in div class.
Things i have already tried
Actions builder - click(), clickandhold()
Javascript executor
I'm currently trying with touch options, tap and by switching to native view but haven't found any success.
If any has encountered the same, a solution will be appreciated.
I want to avoid xPath because that might change in the page I'm working on, and I want to stress that the script is able to find the button, but is not able to click it properly.
You can filter your locator by using class name and index. Like this:
driver.findElementsByXPath("//*[#class='android.widget.ImageView' and #index='0']");
This xpath won't get change on other devices too.
Could you see: Unable to find an element in Browser of the Android emulator using Appium and C# ?
In case of testing web apps in browser the elements should be located as usual elements on the web page ( not as some classes like android.widget.EditText and android.widget.Button).
Upadting appium java client to 1.5.0 (from 1.3.0) solved the issue. Need to check why!

Selenium ie driver cannot switch to window popup

Trying to use the ieDriver.switchTo().window(windowHandle) method to switch to a popup window but my test script stops and does not proceed.
When I close the window manually i get the error
org.openqa.selenium.NoSuchWindowException: Unable to get browser
I know the window exists because I used the ieDriver.getWindowHandles() method to retrieve it.
All my protected mode settings are the same, I even tried to use the 'INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS' technique to no avail. Any other suggestions?
I'm running selenium 2.32.0 with IE9 on a Windows 7 machine.
Above code isfor handling window pops.
If you want to handle javascript popups like alerts, or confrmation popup, you need to use
driver.SwitchTo.alert().accept();
or
driver.SwitchTo.alert().dismiss();
hope it'll help you
maybe the popup is generated, with iframe, then you have to use switchTo.frame();
You should do something like:
WebDriverWait webDriverWait= new WebDriverWait(driver, 5000);
webDriverWait.until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
First you will initialize a WebDriverWait object that will allow you to wait until some condition is met, in this case - alert is present.
Then, the driver will be switched to this alert,