java - 使用 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();
}
}
解决方案
您的 XPath 表达式不是很正确,据我所见,相关文本区域的标题如下所示:
What's on your mind, user1984
所以你需要修改你的定位器来使用XPath
contains()
函数,比如:By.xpath("//textarea[contains(@title,\"What's on your mind\")]")
使用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");
推荐阅读
- sql - 检查任何列是否包含分组后提供的值
- big-o - 计数排序大 O
- spring-boot - SpringBoot 检索现有的原型 bean
- html - 填充网格&
带有 JSON 数据文件
- javascript - 在参考服务器时间的特定日期和时间重定向页面
- java - 不能用不同类型的参数继承
- systemd - 如何让systemd等到进程启动
- php - 如何获取位置id中的最后一个元素
- php - 如何使用 ECB 密码模式和 PKCS7 块填充模式使用 Twofish 加密?
- drupal - 如果我在 Drupal 8 中有两种内容类型,它们之间存在关系,为什么我要在两种内容类型中都放置一个引用字段?