首页 > 解决方案 > 使用 Selenium 和 Java 在 Facebook 中发布状态

问题描述

如何使用 Selenium 和 Java 在 Facebook 中发布状态?我尝试了以下代码,但它不起作用。能够登录,但在发布状态时没有此类元素。登录后我收到通知弹出窗口允许或阻止,如何处理这个也弹出?在我用于测试的代码下方。

public class NewTest {
private WebDriver driver;

 @Test
public void testEasy() throws InterruptedException {

driver.get("https://www.facebook.com/");
Thread.sleep(5000);
driver.findElement(By.id("email")).sendKeys("email");
driver.findElement(By.id("pass")).sendKeys("password" + Keys.ENTER);

Thread.sleep(5000);

driver.findElement(By.xpath("//textarea[@title=\"What's on your mind?\"]")).click();
driver.findElement(By.xpath("//textarea[@title=\"What's on your mind?\"]")).sendKeys("Hello World");
driver.findElement(By.xpath("//textarea[@title=\"What's on your mind?\"]")).sendKeys(Keys.ENTER);

}

@BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver",
    "C:\\Users\\admin\\Desktop\\Test\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
}

@AfterTest
public void afterTest() {
driver.quit();
}

}

标签: javaselenium-webdriver

解决方案


  1. 您的 XPath 表达式不是很正确,据我所见,相关文本区域的标题如下所示:

    What's on your mind, user1984
    

    所以你需要修改你的定位器来使用XPathcontains()函数,比如:

    By.xpath("//textarea[contains(@title,\"What's on your mind\")]")
    
  2. 使用Thread.sleep是一种性能反模式,您应该改用WebDriverWait。示例重构代码:

    driver.get("https://www.facebook.com/");
    WebDriverWait wait = new WebDriverWait(driver, 5);
    wait.until(ExpectedConditions.elementToBeClickable(By.id("email"))).sendKeys("email");
    wait.until(ExpectedConditions.elementToBeClickable(By.id("pass"))).sendKeys("password" + Keys.ENTER);
    
    
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//textarea[contains(@title,\"What's on your mind\")]"))).click();
    wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//textarea[contains(@title,\"What's on your mind\")]"))).sendKeys("Hello World");
    

推荐阅读