繁体   English   中英

我需要一种更有效的方式来按数字顺序处理多个索引

[英]I need a more efficient way to handle multiple indexes in numerical order

我正在尝试制作一个可以自动向DM中的人发送消息的机器人。 我可以通过在此处使用此代码向第一个人发消息,返回,然后向第二个人发消息。

By path3 = By.xpath("//android.widget.LinearLayout[@index='1']"); 
driver.findElement(path3).click(); 

By path4 = By.xpath("//*[@text='Message…']");
driver.findElement(path4).sendKeys("Hello");

 driver.findElement(By.id("com.instagram.android:id/row_thread_composer_button_send")).click();
Thread.sleep(5000);
driver.findElement(By.id("com.instagram.android:id/action_bar_button_back")).click();

By path5 = By.xpath("//android.widget.LinearLayout[@index='2']"); 
driver.findElement(path5).click();

By path6 = By.xpath("//*[@text='Message…']");
driver.findElement(path6).sendKeys("Hello");

driver.findElement(By.id("com.instagram.android:id/row_thread_composer_button_send")).click();
Thread.sleep(5000);
driver.findElement(By.id("com.instagram.android:id/action_bar_button_back")).click();

但这效率不高,因为如果使用此方法,则必须为每个新索引都换一行。

有人知道如何将其重写为更有效的样式吗?

您可以使用for循环和实际的联系人数量。 在这里,我认为这是一个range()

contacts = range(10)
for x in contacts:
    By path3 = By.xpath("//android.widget.LinearLayout[@index='{0}']".format(x);
    driver.findElement(path3).click();

    By path4 = By.xpath("//*[@text='Message…']");
    driver.findElement(path4).sendKeys("Hello");

    driver.findElement(By.id("com.instagram.android:id/row_thread_composer_button_send")).click();
    Thread.sleep(5000);
    driver.findElement(By.id("com.instagram.android:id/action_bar_button_back")).click();

请尝试以下方法:

public void sendMsg() {

    List<MobileElement> paths = (List<MobileElement>) driver.findElements(By.xpath("//*[@class='android.widget.LinearLayout']"));
    WebDriverWait wait = new WebDriverWait(driver, 30);

      for (MobileElement path : paths) 
       {
        By path4 = By.xpath("//*[@text='Message…']");
        driver.findElement(path4).sendKeys("Hello");
         driver.findElement(By.id("com.instagram.android:id/row_thread_composer_button_send")).click();
         wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("com.instagram.android:id/action_bar_button_back"))));
         driver.findElement(By.id("com.instagram.android:id/action_bar_button_back")).click();


    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM