Clear all notification from notification bar of any android device using appium - java

How to clear all notification from notification bar in android using appium in any of the android devices.
I tried
MobileElement clearallnotification=null;
driver.openNotifications();
try {
clearallnotification= driver.findElement(By.xpath("//android.widget.ImageView[contains(#content-desc, 'Clear all notifications')]"));
clearallnotification.click();
}catch(ElementNotFoundException e) {
clearallnotification= driver.findElementById("com.android.systemui:id/delete");
clearallnotification.click();
}
driver.pressKeyCode(AndroidKeyCode.BACK);
But It works only for specific devices how to make it generic for all kind of devices?

The below code will do that. It worked for me.
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from time import sleep
import pytest
class TestScrollAndroid:
"Class to run tests against the Chess Free app"
#pytest.fixture(scope='function')
def driver(self, request):
"Setup for the test"
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '8.1.0'
desired_caps['deviceName'] = 'Realme 2 Pro'
desired_caps['noReset'] = True
desired_caps['udid'] = '2032609e'
desired_caps['allowTestPackages'] = True
# Returns abs path relative to this file and not cwd
desired_caps['app'] = "D:\\Chess Free.apk"
desired_caps['appPackage'] = 'uk.co.aifactory.chessfree'
desired_caps['appActivity'] = '.ChessFreeActivity'
#desired_caps['autoWebview'] = True
#calling_request = request._pyfuncitem.name
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
driver.implicitly_wait(10)
def tearDown():
print("Tear down the test")
driver.quit()
request.addfinalizer(tearDown)
return driver
def test_scroll_notificaion(self,driver):
driver.open_notifications()
def test_clear_all_notification(self, driver):
driver.open_notifications()
if(driver.find_elements_by_id("com.android.systemui:id/clear_all_button"))
element = driver.find_element_by_id("com.android.systemui:id/clear_all_button")
element.click()
assert(not driver.find_elements_by_id("android:id/title"))

If you use Webdriver.IO here is the solution:
$('~Clear,Button').click()

Related

How to get context and switch to webview context

I'm testing a Windows hybrid application, I'm using the codes below to get contexts but I got an UnsupportedCommandException when I launch it.
Here's my code :
public void initialize() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Windows");
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "10");
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Max");
capabilities.setCapability("app", "D:\\Users\\Max\\Desktop\\TI\\ti.exe");
driver = new AppiumDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
Set<String> contextNames = driver.getContextHandles();
for (String contextName : contextNames) {
System.out.println(contextName);
}
driver.context((String) contextNames.toArray()[1]);
}
Here's the output on the Appium Server:
Appium server screen
It says that the command contexts is not recognized.
I'm using :
Appium Desktop v1.20.2
Appium Java client v7.5.1
WinAppDriver v1.2.1
The first of all, you need to get all contexts. More info in official docs
Here how I implemented it in tests.
In some Page Object files I keep Android contexts.
ANDROID_CONTEXTS = {
'webview': 'WEBVIEW_ru.myapp',
'native': 'NATIVE_APP'
}
In some tests I switch context from Native to Webview.
#allure.link(url='https://jira.project.tech/browse/TEST-1', name='TEST-1 - Fill payment form')
#allure.title('Fill payment form')
def test_card_standard_1_month(appdriver):
Paywall(appdriver).press_one_month_button()
PaymentsPage(appdriver).select_card_payment()
PaymentsPage(appdriver).press_payment_button()
appdriver.switch_to.context(ANDROID_CONTEXTS['webview'])
Payform(appdriver).fill_and_submit_payform()
appdriver.switch_to.context(ANDROID_CONTEXTS['native'])
assert SuccessPayment(appdriver).get_successful_payment_title_text() == 'Your subscription is successful!'
You can check all available contexts in your app. More info here -> http://appium.io/docs/en/commands/context/set-context/

GEB: driver is not set as Browser.driver

I'm writing tests with GEB and Spock (I'm new to both).
Driver is declared in GebConfig (updated - the full config file added):
import geb.report.ReportState
import geb.report.Reporter
import geb.report.ReportingListener
import io.github.bonigarcia.wdm.WebDriverManager
import io.qameta.allure.Allure
import org.openqa.selenium.Dimension
import org.openqa.selenium.Point
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeOptions
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.firefox.FirefoxOptions
import org.openqa.selenium.firefox.FirefoxProfile
import org.slf4j.LoggerFactory
import utils.Configuration
def logger = LoggerFactory.getLogger(this.class)
baseUrl = "${Configuration.getStringProperty("BASE_URL")}/${Configuration.getStringProperty("CONTEXT_PATH")}"
baseNavigatorWaiting = true
autoClearCookies = false
cacheDriver = false
reportsDir = 'build/test-reports'
driver = {
WebDriver dr
switch (Configuration.getStringProperty("BROWSER_NAME", "chrome").trim().toLowerCase()) {
case "firefox":
case "ff":
dr = new FirefoxDriver(setUpFirefoxOptions())
break
case "google chrome":
case "chrome":
default:
dr = new ChromeDriver(setUpGoogleChromeOptions())
}
if (Configuration.getBooleanProperty("SET_DRIVER_POSITION", false)) {
dr.manage().window().setPosition(new Point(
Configuration.getIntProperty("BROWSER_X_POS", 0),
Configuration.getIntProperty("BROWSER_Y_POS", 0)))
dr.manage().window().setSize(new Dimension(
Configuration.getIntProperty("BROWSER_WIDTH", 1600),
Configuration.getIntProperty("BROWSER_HEIGHT", 900)));
} else {
dr.manage().window().maximize()
}
return dr
}
static ChromeOptions setUpGoogleChromeOptions() {
WebDriverManager.chromedriver().setup()
ChromeOptions options = new ChromeOptions()
String args = Configuration.getStringProperty("BROWSER_ARGS")
if (args) {
Arrays.stream(args.split("\\s")).each { options.addArguments(it) }
}
return options
}
static FirefoxOptions setUpFirefoxOptions() {
WebDriverManager.firefoxdriver().setup()
FirefoxOptions options = new FirefoxOptions()
FirefoxProfile profile = new FirefoxProfile()
profile.setPreference("network.automatic-ntlm-auth.trusted-uris", "http://,https://")
options.setProfile(profile).setLegacy(false)
return options
}
reportingListener = new ReportingListener() {
void onReport(Reporter reporter, ReportState reportState, List<File> reportFiles) {
def fileGroups = reportFiles.groupBy { it.name.split("\\.")[-1] }
fileGroups['png']?.each {
Allure.addAttachment(it.name, "image/png", new FileInputStream(it), "png")
}
}
}
Test example looks like (BaseTest code is added below):
class SimulationsRunningSpec extends BaseTest {
def "My great test"() {
println("test started")
setup:
to LoginPage
when:
println("when")
then:
println("then")
}
def cleanupSpec() {
browser.quit()
println "Clean up specification"
}
}
And I get the following log sequence:
test started
Created driver
when
then
Created driver
Clean up specification
So the driver gets created when to LoginPage is called.
Issue:
It is not set as Browser driver, so when the browser.quit() is called, a new instance is created and then closed (the first one still is opened).
Questions:
How to set the driver to browser properly to close it then via browser.quit()?
Am I right assuming that if I need to create a driver in setupSpec I can simply call to LoginPage there? Or what is the best way to init the driver in preconditions?
UPDATE:
After some debugging I found out that for some reason, browser gecomes null and is created again in cleanupSpec(). It doesn't matter whether the Spec extends Geb classes of custom base class. This reproduces my issue:
class TestSpec extends GebReportingSpec {
def setupSpec() {
to Page
println "setupSpec browser: $browser"
}
def setup(){
println "setup browser: $browser"
}
def "My first test"() {
println("test started")
when:
println ''
then:
println ''
}
def cleanup() {
println "cleanup browser: $browser"
}
def cleanupSpec() {
println "cleanupSpec browser: $browser"
}
}
This produces the following output:
setupSpec browser: geb.Browser#4beeb0e
setup browser: geb.Browser#4beeb0e
test started
cleanup browser: geb.Browser#4beeb0e
cleanupSpec browser: geb.Browser#5c73f672
The last two rows show that the browser object in cleanupSpec is different from created object in setupSpec.
I'm not sure, why the browser was closed before your cleanupSpec. Probably some other mechanism already took care of it.
The fact that you are getting a different instance in your cleanupSpec however is simply due to the fact, that getBrowser is implemented as a lazy getter. It creates a new instance if necessary, as you can see in the code.
Generally you don't need to call browser.quit using Geb. Geb takes care of that just fine.
Update
Here is what happens in GebSpec and YourSpec:
GebSpec.setupSpec is triggered ⇒ _browser is null
YourSpec.setupSpec is triggered ⇒ _browser is still null unless you use it here
GebSpec.setup is triggered ⇒ _browser is not changed
YourSpec.setup is triggered ⇒ _browser might be changed
YouSpec's first feature is triggered ⇒ _browser is used, so it won't be null anymore
YourSpec.cleanup is triggered ⇒ _browser is not changed
GebSpec.cleanup is triggered ⇒ _browser is set to null! As you can see in the code, resetBrowser is called unless YourSpec is #Stepwise and that sets _browser to null as you can see here.
YourSpec.cleanupSpec is triggered ⇒ _browser is null unless you use it, so it gets reinitialized
GebSpec.cleanupSpec is triggered ⇒ _browser is still null
This seems strange that you are seeing the browser reinitialise for the cleanup, what you have shown is correct.
For point 1: You are setting it correctly within the gebconfig.
For point 2: You don't need to initialise the browser within the setupSpec(), the config entry is all you need.
The browser should close automatically once all tests are run, UNLESS you have added the following to your gebconfig and set to false:
quitCachedDriverOnShutdown = false
setupSpec() is called after all methods within the spec have been run. Is what you have shown us the only code within your spec? Is your spec extending GebSpec or GebReportingSpec or a custom base class?
The only other thing i can think is that you have 2 tests in that spec, so you're seeing "Created driver" twice, and the cleanUpSpec() is called after all tests are run so you see that called at the end. If you had called cleanup() it would run between each test.

How to set Proxy Authentication in seleniumWebdriver for Chrome Browser

I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.
This is the code I'm using in my driver initializing process
package com.misyn.ess.ui;
import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
*
* #author User
*/
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
private DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
//Set the location of the ChromeDriver
System.setProperty(driverName, driverPath);
//Create a new desired capability
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// Create a new proxy object and set the proxy
Proxy proxy = new Proxy();
proxy.setHttpProxy("192.168.0.200:3128");
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
//Add the proxy to our capabilities
capabilities.setCapability("proxy", proxy);
//Start a new ChromeDriver using the capabilities object we created and added the proxy to
driver = new ChromeDriver(capabilities);
//Navigation to a url and a look at the traffic logged in fiddler
driver.navigate().to(baseUrl);
// System.setProperty(driverName, driverPath);
// driver = new ChromeDriver();
// driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks
the currently answered one is only for
As of Selenium 3.4 it is still in beta
Right now implementation is only done for InternetExplorerDriver
Where I'm using selenium 3.0 and Google Chrome as my web browser.
You can do via MultiPass for HTTP basic authentication
Download the extension from
https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah
Download the extension as crx. You can get it as crx from chrome-extension-downloader
After that the config is simple.
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
/**
*
* #author Phystem
*/
public class ChromeAuthTest {
WebDriver driver;
public ChromeAuthTest() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
}
private void initDriver() {
ChromeOptions cOptions = new ChromeOptions();
cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
driver = new ChromeDriver(cOptions);
configureAuth(
"https://the-internet.herokuapp.com/basic_auth",
"admin",
"admin");
}
private void configureAuth(String url, String username, String password) {
driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
driver.findElement(By.id("url")).sendKeys(url);
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.className("credential-form-submit")).click();
}
public void doTest() {
initDriver();
driver.get("https://the-internet.herokuapp.com/basic_auth");
System.out.println(driver.getTitle());
driver.quit();
}
public static void main(String[] args) {
new ChromeAuthTest().doTest();
}
}
I have used a sample site for testing.
Provide your url,username and password in the configure Auth function and try
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
public DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
System.setProperty(driverName, driverPath);
Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setSslProxy("192.168.0.200" + ":" + 3128);
proxy.setFtpProxy("192.168.0.200" + ":" + 3128);
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
driver = new ChromeDriver(desiredCapabilities);
driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The proxy setting has been added with desired capabilities to pass values to proxy authentication,worked finally
This code (from Avishka Perera's answer) does not work for me:
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
The username and password set in this way do not take effect for the http/https proxy - the Proxy Authentication box still popped up.
I'm using Selenium java 3.141.0, ChromeDriver 2.33 and chrome 70. What works for me is to follow Mike's answer here Selenium using Python: enter/provide http proxy password for firefox .
Create the zip file, then add the extension like this:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("src/test/resources/proxy.zip"));
WebDriver driver = new ChromeDriver(chromeOptions);
One catch is that the above code will run into error if you set "--headless" argument because chrome in headless mode cannot have extension (Is it possible to run Google Chrome in headless mode with extensions?). If your Chrome runs in Docker container and cannot show the UI, then to get this solution work, you'll need to run with Xvfb instead of in headless mode.
Simple method to add authenticated proxy using selenium wire in Both firefox and chrome
In python
Step:1
pip3 install selenium-wire
Step:2
from seleniumwire import webdriver
from selenium import webdriver
step:3
Add proxy in below-mensioned format
proxy= "username:password#ip:port"
options = {'proxy': {'http': proxy, 'https': proxy, 'no_proxy': 'localhost,127.0.0.1,dev_server:8080'}}
step:4
pass proxy as an argument
CHROME
driver = webdriver.Chrome(options=chrome_options, executable_path="path of chrome driver", seleniumwire_options=options)
Firefox
driver = webdriver.Firefox(seleniumwire_options=options, executable_path="path of firefox driver", options=firefox_options)
step:5
Verify proxy applied by requesting the url https://whatismyipaddress.com/
time.sleep(20)
driver.get("https://whatismyipaddress.com/")
Note:
But selenium log shows it runs in without proxy because we are using an external package to apply proxy.
I know this is an old thread, still leaving a solution which worked for me using browsermob proxy, for someone who still needs an option.
Maven dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>
Java Code:
// I am using firefox
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");
BrowserMobProxy browsermobProxy = new BrowserMobProxyServer();
browsermobProxy.setChainedProxy(new InetSocketAddress(PROXY_HOSTNAME, PROXY_PORT));
browsermobProxy.chainedProxyAuthorization(PROXY_USERNAME, PROXY_PASSWORD, AuthType.BASIC);
browsermobProxy.start(0);
FirefoxBinary firefoxBinary = new FirefoxBinary();
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary );
firefoxOptions.setProfile(firefoxProfile);
firefoxOptions.setProxy(ClientUtil.createSeleniumProxy(browsermobProxy));
WebDriver webDriverWithProxy = new FirefoxDriver(firefoxOptionsWithProxy);
webDriverWithProxy.get("https://stackoverflow.com/");
The approach that worked perfectly fine for me is by using AutoIT.
Install autoIT and prepare a simple script as shown in the picture attached and execute the script file from your testscript using Runtime.getRuntime().exec("\YOUR_SCRIPT.exe") before navigating to the baseURL.

browserMob proxy with phantomjs throws "java.net.UnknownHostException" for http protocol

Trying to use PhantomJS(com.codeborne:phantomjsdriver:1.2.1) for some headless browser testing along with BrowserMob Proxy(browsermob-proxy-2.0-beta-9) to capture HAR files and Javascript execution.
It works for urls with https(eg. https://www.google.com) and I get the HAR.
However for http(eg. http://www.google.com) I get the following error in the BrowserMob logs
INFO 02/02 22:45:03 n.l.b.p.j.h.HttpSer~ - Version Jetty/5.1.x
INFO 02/02 22:45:03 n.l.b.p.j.u.Contain~ - Started HttpContext[/,/]
...
INFO 02/02 22:46:29 n.l.b.p.h.BrowserMo~ - java.net.UnknownHostException: www.google.com when requesting http://www.google.com/
INFO 02/02 22:46:54 n.l.b.p.j.u.Threade~ - Stopping Acceptor ServerSocket[addr=/0.0.0.0,localport=13000]
...
Following is how I setup PhantomJS
public RemoteWebDriver getDriverInstance() {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setJavascriptEnabled(true);
//code to get Proxy is below
capabilities.setCapability(CapabilityType.PROXY, getProxyObject());
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "./bin/phantomjs");
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS, new String[] {"--web-security=no", "--ssl-protocol=any", "--ignore-ssl-errors=yes"});
WebDriver webDriver = new PhantomJSDriver(capabilities);
return (RemoteWebDriver) webDriver;
}
public Proxy getProxyObject() {
Proxy proxy = new Proxy();
//publicIp is localhost for testing purposes.
String proxyLocation = this.getPublicIp() + ":" + this.getBrowserMobProxyPort();
proxy.setHttpProxy(proxyLocation);
proxy.setFtpProxy(proxyLocation);
proxy.setSslProxy(proxyLocation);
return proxy;
}
Still looking for a solution.
Is it normal to expect such messages from BrowserMob?
I, most probably have not setup something correctly or missed a part. Would be awesome if anyone who has faced this issue, help me out or point me to a solution. I have done some searching but not found a solution that resolves this.
Also if there is additional information needed, please let me know.
I am using a newer version of BrowserMob Proxy, but the following Scala code works for me in loading HTTP and HTTPS websites:
import java.io.File
import net.anthavio.phanbedder.Phanbedder
import net.lightbody.bmp.BrowserMobProxyServer
import net.lightbody.bmp.client.ClientUtil
import net.lightbody.bmp.core.har.HarEntry
import org.apache.commons.io.FileUtils
import org.openqa.selenium.OutputType
import org.openqa.selenium.phantomjs.PhantomJSDriver
import org.openqa.selenium.phantomjs.PhantomJSDriverService._
import org.openqa.selenium.remote.{CapabilityType, DesiredCapabilities}
import scala.collection.JavaConversions._
object PhantomJSTest {
def main(args: Array[String]) {
val bm = new BrowserMobProxyServer
bm.start(0)
val proxy = ClientUtil.createSeleniumProxy(bm)
val phantomjs = Phanbedder.unpack()
val capabilities = new DesiredCapabilities
capabilities.setCapability(CapabilityType.PROXY, proxy)
capabilities.setCapability(PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
phantomjs.getAbsolutePath())
capabilities.setCapability(PHANTOMJS_CLI_ARGS,
Array[String]("--web-security=no",
"--ssl-protocol=any",
"--ignore-ssl-errors=yes"))
val driver = new PhantomJSDriver(capabilities)
run(bm, driver, "http://www.google.com")
run(bm, driver, "https://www.google.com")
driver.quit
bm.stop
}
def run(bm: BrowserMobProxyServer, driver: PhantomJSDriver, url: String) {
bm.newHar(url)
driver.get(url)
val har = bm.getHar
har.getLog.getEntries.foreach { e: HarEntry =>
println(e.getRequest.getUrl)
}
val file = new File(s"screenshot-${System.currentTimeMillis}.png")
FileUtils.copyFile(driver.getScreenshotAs(OutputType.FILE), file)
println(s"Captured loading of ${url} screenshot to ${file.getCanonicalPath}")
}
}
Here are the libraries I am using (from my build.gradle file):
compile 'commons-io:commons-io:2.4'
compile 'org.slf4j:slf4j-simple:1.7.16'
compile 'net.lightbody.bmp:browsermob-core-littleproxy:2.1.0-beta-4'
compile 'org.seleniumhq.selenium:selenium-java:2.45.0'
compile 'com.codeborne:phantomjsdriver:1.2.1'
compile 'net.anthavio:phanbedder-2.1.1:1.0.0'
Hope this helps you debug the issue you are running in to.

How to make comment on facebook post using selenium

public class testngprj {
public String baseurl="https://www.facebook.com/";
public WebDriver dv= new FirefoxDriver();
#Test (priority=0) public void gettitleverified() {
String expectedTitle="Facebook - Log In or Sign Up";
String actualtitle=dv.getTitle();
AssertJUnit.assertEquals(expectedTitle, actualtitle);
}
#Test (priority=1) public void validlogin() {
dv.findElement(By.id("email")).sendKeys("username");
dv.findElement(By.id("pass")).sendKeys("pass");
dv.findElement(By.id("loginbutton")).click();
}
#Test (priority=2) public void makecomment() {
//JavascriptExecutor jse = (JavascriptExecutor)dv;
//jse.executeScript("window.scrollBy(0,2000)", "");
dv.findElement(By.xpath("/html/body/div[1]/div[1]/div/div/div/div[1]/div/div/div[2]/ul/li[1]/a/span")).click();
dv.findElement(By.className("_209g _2vxa")).sendKeys("Nice one");
dv.findElement(By.className("_209g _2vxa")).sendKeys(Keys.ENTER);
}
#BeforeTest public void beforeTest() {
dv.get(baseurl);
}
#AfterTest public void afterTest()
{
}
}
Finally I did it ! Check this chunk of code in python.
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
firefox_options = Options()
firefox_options.add_argument('--dns-prefetch-disable')
firefox_options.add_argument('--no-sandbox')
firefox_options.add_argument('--lang=en-US')
browser = webdriver.Firefox(executable_path='/home/coder/Documents/Projects/socialbot/geckodriver', firefox_options=firefox_options)
browser.get('https://www.facebook.com/')
signup_elem = browser.find_element_by_id('email')
signup_elem.send_keys('EMAILHERE')
login_elem = browser.find_element_by_id('pass')
login_elem.send_keys('PASSHERE')
ins = browser.find_elements_by_tag_name('input')
for x in ins:
if x.get_attribute('value') == 'Log In':
x.click() # here logged in
break
#then key here move to mobile version as that doesn't support javascript
browser.get('https://m.facebook.com')
el = browser.find_element_by_name('query')
el.send_keys('antony white')
el.send_keys(Keys.ENTER)
sleep(3)
temp= ''
ak = browser.find_elements_by_tag_name('a')
for a in ak:
if a.get_attribute('href').endswith('search'):
a.click()
temp = a.get_attribute('href')[:a.get_attribute('href').find("?")]
break
# CLICK TIMELINE
browser.get(temp+'?v=timeline')
sleep(10)
# find last post (occurance of comment)
as_el = browser.find_elements_by_tag_name('a')
for a in as_el:
print(a.text)
if 'omment' in a.text.strip():
a.click()
break
sleep(10)
# do actual comment
ins = browser.find_element_by_id('composerInput')
ins.send_keys('Best cars !')
# submit input
ins = browser.find_elements_by_tag_name('input')
for x in ins:
if 'omment' in x.get_attribute('value'):
x.click()
break
Move to mobile facebook version saved my life. The last. I tried to do that with facebook api. But their Api REALLY SUCKS ! I did, waste a lot of time on their graph api, that was a disaster. And I think facebook want to kill somebody with their graph api.
Try this:
dv.findElement(By.xpath("//a[#class='UFILikeLink']")).click();
Thread.sleep(2000);
dv.findElement(By.xpath("//a[#class='comment_link']")).click();
dv.findElement(By.className("_54-z")).sendKeys("hgfghjkj");
Thread.sleep(2000);
dv.findElement(By.className("_54-z")).sendKeys(Keys.RETURN);

Categories

Resources