通过selenium在paytm主页上发起搜索

问题描述 投票:-1回答:2

以下是我想通过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);
    }
}
java selenium selenium-webdriver paytm webdriverwait
2个回答
-1
投票

@ 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
  • 当JavaScripts和Ajax Calls仍处于活动状态时,带有此页面标题的初始页面是间歇性的。因此,在发送搜索字符串之前,您需要按如下方式引入WebDriverWait:
  • 理想方法: 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 !
  • 浏览器快照:

paytm


1
投票

问题是您需要等待页面完全加载。有一个运行onload页面的ajax脚本,它可以在搜索输入文本框中执行一些操作。页面完全加载后,body标签包含style属性。 Wait通过使用ExpectedConditionsattributeCOntainsWebDriverWait获得此属性。

试试这个代码 -

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");
© www.soinside.com 2019 - 2024. All rights reserved.