以下是我想通过Selenium在paytm上实现自动化的步骤。
脚步:-
1.Launch Paytm。
2.在paytm页面顶部显示的搜索框中输入任意关键字。例如“移动”
3.按Enter键导航到搜索结果页面。
问题:搜索框中写的关键字会自动删除
我的代码:
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class XPath {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\ProgramFiles\\Work\\ChromeDriver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("https://paytm.com");
//driver.findElement(By.xpath("//input[@placeholder='Search for a Product , Brand or Category']")).sendKeys("mobile");
driver.findElement(By.xpath("//input[@placeholder='Search for a Product , Brand or Category']")).sendKeys(Keys.ENTER);
}
}
@ Grasshopper的分析是正确的,您需要等待页面完全加载。我使用您自己的代码进行了一个小测试,以便在调用url后立即检索页面标题:
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://paytm.com");
System.out.println(driver.getTitle());
Recharge - Online Mobile Recharge & Win 100% Cashback | Paytm.com
System.setProperty("webdriver.chrome.driver", "C:\\path\\to\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://paytm.com");
System.out.println(driver.getTitle());
new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Paytm.com – Digital & Utility Payment, Entertainment, Travel, Payment Gateway & more Online !"));
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//input[@placeholder='Search for a Product , Brand or Category']")).sendKeys("mobile");
driver.findElement(By.xpath("//input[@placeholder='Search for a Product , Brand or Category']")).sendKeys(Keys.ENTER);
Recharge - Online Mobile Recharge & Win 100% Cashback | Paytm.com
Paytm.com – Digital & Utility Payment, Entertainment, Travel, Payment Gateway & more Online !
问题是您需要等待页面完全加载。有一个运行onload页面的ajax脚本,它可以在搜索输入文本框中执行一些操作。页面完全加载后,body标签包含style属性。 Wait通过使用ExpectedConditions
和attributeCOntains
的WebDriverWait
获得此属性。
试试这个代码 -
new WebDriverWait(driver, 3).until(ExpectedConditions.attributeContains(By.tagName("body"), "style", "overflow: visible;"));
WebElement srch = driver.findElement(By.cssSelector("input[type='search']"));
srch.sendKeys("Hello");