driver.get("https://www.facebook.com/sachin.aryal");
driver.findElement(By.name("xhpc_message_text")).sendKeys("Testing Java and Selenium");
driver.findElement(By.xpath("//*[@id='u_0_1a']/div/div[6]/div/ul/li[2]/button")).click();
代码的最后一行不能工作。如何在facebook上设置Post按钮的XPath ?
我知道你已经标记了自己的答案,但这不是正确的方法。Selenium中有内置的方法来执行等待,例如等待一个元素可点击。
driver.get("https://www.facebook.com/sachin-aryal/");
driver.findElement(By.name("xhpc_message_text")).sendKeys("Testing Java and Selenium");
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button/span[.="Post"]"))).click();
我注意到它的工作,当你第一次滚动到视图按钮,尝试添加之前点击张贴:
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,259)","");
试试下面的代码。它一定对你有用。
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Facebook_login {
public static void main(String[] args) throws InterruptedException {
String user_name = "facebook_user_name";
String pwd = "facebook_password";
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.facebook.com");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.findElement(By.name("email")).clear();
driver.findElement(By.name("email")).sendKeys(user_name);
driver.findElement(By.name("pass")).clear();
driver.findElement(By.name("pass")).sendKeys(pwd);
driver.findElement(By.xpath("//input[contains(@value,'Log In')]")).click();
Thread.sleep(10000);
System.out.println("logged in successfully");
WebElement notification = driver.findElement(By.xpath("//a[contains(@action,'cancel')]"));
if(notification.isDisplayed()) {
System.out.println("Notification is present");
notification.click();
}
WebElement status =driver.findElement(By.xpath("//textarea[@name='xhpc_message']"));
status.sendKeys("Hello");
Thread.sleep(3000);
WebDriverWait wait = new WebDriverWait(driver,30);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Post']"))).click();
}
}