I am trying to write a script that fetches Estonian zip codes. Here is the code:
import com.gargoylesoftware.htmlunit.BrowserVersion
import org.openqa.selenium.{By, WebDriver}
import org.openqa.selenium.htmlunit.HtmlUnitDriver
object Application {
def main(args: Array[String]) {
val driver = new HtmlUnitDriver(BrowserVersion.CHROME)
driver.setJavascriptEnabled(true)
query(driver, "Pelguranna 9")
}
def query(driver: WebDriver, query: String) {
driver.get("https://www.omniva.ee/eng")
val tab = driver.findElement(By.xpath("//*[#class='search-tabs']/li[1]"))
tab.click()
val name = driver.findElement(By.name("zip_address"))
name.sendKeys(query)
name.submit()
val result = driver.findElement(By.xpath("//*[#id='zip_container']/p[0]"))
print(result)
}
}
Basically, you should go to URL, click on 'FIND A ZIP CODE' tab, insert address, press enter and take first result.
But I am getting an error:
Driver info: driver.version: unknown
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.verifyCanInteractWithElement(HtmlUnitWebElement.java:282)
at org.openqa.selenium.htmlunit.HtmlUnitWebElement.sendKeys(HtmlUnitWebElement.java:326)
at Application$.query(grab.scala:20)
at Application$.main(grab.scala:10)
at Application.main(grab.scala)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
I have never written anything like this before, so do not know what this error means. Can anyone say what is the problem with my code?
I found the following issues with your code.
The XPaths for elements are wrong.
There is not enough wait time between operations.
I am a JAVA guy and was able to get the zip code using the following code. I believe you can make the changes to python.
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new HtmlUnitDriver(BrowserVersion.CHROME);
((HtmlUnitDriver) driver).setJavascriptEnabled(true);
test(driver, "Pelguranna 9");
}
public static void test(WebDriver driver, String query) throws InterruptedException {
driver.get("https://www.omniva.ee/eng");
Thread.sleep(5000);
WebElement tab = driver.findElement(By.xpath("//a[.='Find a ZIP code'][#href='#search-zip']"));
tab.click();
WebElement name = driver.findElement(By.name("zip_address"));
name.sendKeys(query);
name.submit();
Thread.sleep(10000);
WebElement result = driver.findElement(By.xpath("//*[#id='zip_container']/p/span"));
System.out.println(result.getText());
}
Hope this helps you.
Related
I'm running a selenium framework in Java which is using a DriverFactor class, Constant class, a ReadConfigFile class and a config.properities file to store relevant data in which I can call through the DriverFactory.
However, when I run a feature file, I get an error almost straight away citing, 'Unable to load browser: null'.
I believe this is happening as the config file isn't being read properly, so therefore returns 'null' and then fails. I just can't seem to be able to fix the issue.
I have added e.printstacktrace(); to try and get a better idea of where the issue is originating, but I'm yet to imply a fix.
DriverFactory.java
package utils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
// Read Config
ReadConfigFile file = new ReadConfigFile();
String browser = file.getBrowser();
switch (browser) {
/*
* switch statement lets you select the browser you want
*/
case "firefox":
// code
if (null == driver) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
driver = new FirefoxDriver();
}
break;
case "chrome":
// code
if (null == driver) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
e.printStackTrace();
}// finally {
//driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
//}
return driver;
}
}
Constant. java
package utils;
public class Constant {
/*
* Config Property File
*/
public final static String CONFIG_PROPERTIES_DIRECTORY = "config.properties";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\chromedriver.exe";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\geckondriver.exe";
}
ReadConfigFile.java
package utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getBrowser() {
if (prop.getProperty("browser") == null)
return "";
return prop.getProperty("browser");
}
}
config.properities
browser=chrome
Console/StackTrace print out
Feature: Log into account
Existing user should be able to log into account using correct credentials
Scenario Outline: Login to account with credentials # C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:4
Given user navigates to "<url>"
When user clicks on the login portal button
And User enters username "<username>"
And User enters password "<password>"
And User clicks on the login button
Then user should be presented with validation "<message>"
Examples:
Unable to load browser: null
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at utils.ReadConfigFile.<init>(ReadConfigFile.java:15)
at utils.DriverFactory.getDriver(DriverFactory.java:16)
at stepDefinitions.MasterHooks.setup(MasterHooks.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaHookDefinition.execute(JavaHookDefinition.java:60)
at cucumber.runtime.Runtime.runHookIfTagsMatch(Runtime.java:224)
at cucumber.runtime.Runtime.runHooks(Runtime.java:212)
at cucumber.runtime.Runtime.runBeforeHooks(Runtime.java:202)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:40)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Unable to load browser: null
java.lang.NullPointerException
at java.util.Properties$LineReader.readLine(Properties.java:434)
at java.util.Properties.load0(Properties.java:353)
at java.util.Properties.load(Properties.java:341)
at utils.ReadConfigFile.<init>(ReadConfigFile.java:15)
at utils.DriverFactory.getDriver(DriverFactory.java:16)
at stepDefinitions.GenericWebSteps.user_navigates_to(GenericWebSteps.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at cucumber.runtime.Utils$1.call(Utils.java:40)
at cucumber.runtime.Timeout.timeout(Timeout.java:16)
at cucumber.runtime.Utils.invoke(Utils.java:34)
at cucumber.runtime.java.JavaStepDefinition.execute(JavaStepDefinition.java:38)
at cucumber.runtime.StepDefinitionMatch.runStep(StepDefinitionMatch.java:37)
at cucumber.runtime.Runtime.runStep(Runtime.java:300)
at cucumber.runtime.model.StepContainer.runStep(StepContainer.java:44)
at cucumber.runtime.model.StepContainer.runSteps(StepContainer.java:39)
at cucumber.runtime.model.CucumberScenario.run(CucumberScenario.java:44)
at cucumber.runtime.model.CucumberScenarioOutline.run(CucumberScenarioOutline.java:46)
at cucumber.runtime.model.CucumberFeature.run(CucumberFeature.java:165)
at cucumber.runtime.Runtime.run(Runtime.java:122)
at cucumber.api.cli.Main.run(Main.java:36)
at cucumber.api.cli.Main.main(Main.java:18)
Scenario Outline: Login to account with credentials # C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:14
Given user navigates to "http://www.webdriveruniversity.com" # GenericWebSteps.user_navigates_to(String)
java.lang.NullPointerException
at stepDefinitions.GenericWebSteps.user_navigates_to(GenericWebSteps.java:21)
at ✽.Given user navigates to "http://www.webdriveruniversity.com"(C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:5)
When user clicks on the login portal button # GenericWebSteps.user_clicks_on_the_login_portal_button()
And User enters username "tomdale" # GenericWebSteps.user_enters_a_username(String)
And User enters password "testuser1" # GenericWebSteps.user_enters_a_password(String)
And User clicks on the login button # GenericWebSteps.user_clicks_on_the_login_button()
Then user should be presented with validation "validation failed" # GenericWebSteps.user_should_be_presented_with_validation(String)
Failed scenarios:
C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:14 # Scenario Outline: Login to account with credentials
1 Scenarios (1 failed)
6 Steps (1 failed, 5 skipped)
0m0.076s
java.lang.NullPointerException
at stepDefinitions.GenericWebSteps.user_navigates_to(GenericWebSteps.java:21)
at ✽.Given user navigates to "http://www.webdriveruniversity.com"(C:/Users/Tom/Desktop/CucumberFramework/CucumberFramework/src/test/java/features/Login.feature:5)
I expect either a chrome driver instance or gecko driver instance to load and my test to execute.
Actual results, I received 'Unable to load browser: null' error
In your these lines
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
you have initialised input as null and then in prop.load(input), you're loading a input which is still null. That is why there is a NPE.
For anyone struggling with a similar issue, I managed to work it out in the end.
So first of all, within the ReadConfigFile.java, within the try statement, you will want set the initialization of ReadConfig to input. As shown below..
try {
input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
Also, within your Constant.java class, set the CONFIG_PROPERTIES_DIRECTORY to the file path where your config.properties file is stored, like below:
package utils;
public class Constant {
/*
* Config Property File
*/
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\chromedriver.exe";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\java\\resources\\geckondriver.exe";
}
If you then run configurations on the chosen Feature file, it should create an instance of your chosen Web Driver and your test should run as normal.
I am trying to upload the file in selenium using java. When I run my test case then it passed every time but the file is not uploading. See below site and my code where I performing.
Site URL: https://files.fm/
Xpath where i want to upload: //input[#name='file_upload[]']
Note: If this xpath is incorrect then please update in comment.
Code:
#BeforeTest
public void OpenBrowser() {
System.setProperty("webdriver.chrome.driver", "./driver/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://files.fm/");
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void FileUpload() throws InterruptedException, IOException {
Thread.sleep(2000);
WebElement file = driver.findElement(By.xpath("//input[#name='file_upload[]']"));
file.sendKeys("C:/Users/Admin/Pictures/Lighthouse.jpg");
}
use below code :
WebElement file = driver.findElement(By.xpath("//input[#id='file_upload']//following-sibling::input"));
file.sendKeys("C:/Users/Admin/Pictures/Lighthouse.jpg");
WebElement startUploadButton = driver.findElement(By.xpath("//div[#id='savefiles']//div"));
startUploadButton.click();
Hope that helps you:)
You choosed the wrong input. I tried to send to the other input and it worked
Here is xpath of it.
String inPath = "//*[#id='uploadifive-file_upload']/input[2]";
My framework consists of TestNG + Cucumber +Jenkins , I'm running the job using bat file configuration in jenkins.
My doubt is , I have a class file to launch the browser and I pass string value to if loop saying ,
if string equals "chrome" then launch the Chrome browser and soon.
Is there a way to pass the chrome value from jenkins into class file ?
example :
public class launch(){
public static String browser ="chrome"
public void LaunchBrowser() throws Exception{
if (browser.equalsIgnoreCase("chrome"))
{
launch chrome driver
}
}
Now i would like to pass the static string value from jenkins ,
Help is appreciated.
Thanks in advance.
You can do something like below
public class Launch {
//You would be passing the Browser flavor using -Dbrowser
//If you don't pass any browser name, then the below logic defaults to chrome
private static String browser =System.getProperty("browser", "chrome");
public void LaunchBrowser() throws Exception {
if (browser.equalsIgnoreCase("chrome")) {
//launch chrome driver
}
}
}
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);
EDIT:
To make this whole thing clear, what im trying to do it make the program go to http://www.ultimateprivateservers.com/index.php?a=in&u=IkovPS and click the red "enter and vote" button
What I'm trying to do is access a webpage programmatically and click a href button that goes like this:
Enter and vote
I've looked at a few tuts with htmlUnit and I can't seem to get this working. What am I doing wrong? Could someone point me in the right direction? I'm not very good with java so it will get confusing.
Here is my code:
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
public class HtmlUnitFormExample {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://www.ultimateprivateservers.com/index.php?a=in&u=IkovPS");
HtmlLink enterAndVoteButton =
page.getElementByName("btn btn-danger");
page=enterAndVoteButton.click();
HtmlDivision resultStatsDiv =
page.getFirstByXPath("//div[#id='vote_message_fail']");
System.out.println(resultStatsDiv.asText());
webClient.closeAllWindows();
}
}
and here is the console log:
SEVERE: IOException when getting content for iframe: url=[http://a.tribalfusion.com/p.media/aPmQ0x0qPp4WYBPGZbE4PJZdodZanVdfb0bQjYrBeXaisRUvDUFB5WHn0mFBoRU7y1T3s5TUj2qfXmEjIYbYgUHBUoP7Cns7uptfG5Evl5teN5ABLpbbL0V7R1VF3XGjNmqJQ3FQ2WFJBW6Q2QEf1ScUMQdUOYtbuTPbx2G32XrnZcVmun4PQgQmnH4HQrXHBAMTAJplZd1Wp/3002246/adTag.html]
org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:188)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:178)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1313)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1230)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:338)
at com.gargoylesoftware.htmlunit.html.BaseFrameElement.loadInnerPageIfPossible(BaseFrameElement.java:184)
at com.gargoylesoftware.htmlunit.html.BaseFrameElement.loadInnerPage(BaseFrameElement.java:122)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadFrames(HtmlPage.java:1993)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:238)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:475)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:342)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:407)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:392)
at HtmlUnitFormExample.main(HtmlUnitFormExample.java:7)
Caused by: org.apache.http.HttpException: Unsupported Content-Coding: none
at org.apache.http.client.protocol.ResponseContentEncoding.process(ResponseContentEncoding.java:98)
at org.apache.http.protocol.ImmutableHttpProcessor.process(ImmutableHttpProcessor.java:139)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:200)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
... 14 more
Apr 18, 2015 5:28:37 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'application/x-javascript'.
Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[*] attributeName=[name] attributeValue=[btn btn-danger]
at com.gargoylesoftware.htmlunit.html.HtmlPage.getElementByName(HtmlPage.java:1747)
at HtmlUnitFormExample.main(HtmlUnitFormExample.java:10)
Any help is much appreciated.
I took a look at the page and was able to cast a vote using a slightly different method. I prefer to use Selenium (http://www.seleniumhq.org/download/). I was able to use Selenium in Java to successfully cast a vote using the very crude code below. You can edit and optimize this code to your specific needs. I watched the whole process in an Internet Explorer driver but you could also use PhantomJS (http://phantomjs.org/download.html) as your driver if you do not want the window to show. Here is my simple code, the second argument of the setProperty method is the path to your driver executable this will be unique to your computer (you can download the IE driver on the Selenium downloads page as well):
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
public class SeleniumTest()
{
public static void main(String[] args)
{
try
{
System.setProperty("webdriver.ie.driver"," IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.ultimateprivateservers.com/index.php?a=in&u=IkovPS");
Thread.sleep(3000); //use the wait as shown below
WebElement button = driver.findElement(By.linkText("Enter and vote"));
button.click();
driver.close();
driver.quit();
}catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A better way to wait for the page to load would be like this:
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Enter and vote")));
You could also find the button using the class like:
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("btn-danger")));