【问题标题】:Hover over dropdown menu in Amazon将鼠标悬停在亚马逊的下拉菜单上
【发布时间】:2019-04-01 17:43:33
【问题描述】:

我只想将鼠标悬停在亚马逊网站上的“部门”下拉列表上。代码看起来不错,但列表未显示。这是我要显示的部门下拉列表

这是我的代码

    driver = new ChromeDriver();
    driver.get("https://www.amazon.com");
    Actions actions = new Actions(driver);
    WebElement ele = driver.findElement(By.xpath("//span[@class='nav-line-2']"));
    Thread.sleep(300);
    actions.moveToElement(ele);
    actions.perform();
    actions.perform();

【问题讨论】:

    标签: java selenium selenium-webdriver action webdriverwait


    【解决方案1】:

    看起来 xpath 不是唯一的,并且具有相同的定位器,在页面中定位 6 个元素。当我们有多个具有相同定位器的元素时,硒会选择第一个元素。就您而言,不幸的是,“部门”不是该定位器的第一个元素。

    将您的 xpath 更改为以下内容:[Tested & working]

    //span[@class='nav-line-2' and contains(.,'Departments')]
    

    【讨论】:

    • 这对吗 WebElement ele = driver.findElement(By.xpath("//span[@class='nav-line-2' and contains(.,'Departments')]")) ;
    • 部门括号中的 ., 是什么?
    • 对不起,它成功了,谢谢,我复制了你的代码,以为我的代码是一样的,所以我想不是这样,谢谢 Dhamo
    • 表示text(),因为整个'Department'文本都在span元素中,我们可以使用“.”而不是“文本()”。在少数情况下您将无法使用详细here
    【解决方案2】:

    要鼠标悬停 将文本作为Departments 的元素,您需要诱导WebDriverWait 以使所需的元素可见 并将moveToElement() 方法与perform() 方法结合使用,您可以使用以下解决方案:

    • 代码块:

      import org.openqa.selenium.By;
      import org.openqa.selenium.WebDriver;
      import org.openqa.selenium.WebElement;
      import org.openqa.selenium.chrome.ChromeDriver;
      import org.openqa.selenium.chrome.ChromeOptions;
      import org.openqa.selenium.interactions.Actions;
      import org.openqa.selenium.support.ui.ExpectedConditions;
      import org.openqa.selenium.support.ui.WebDriverWait;
      
      public class amazon_com_Departments {
      
          public static void main(String[] args) {
      
              System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
              ChromeOptions options = new ChromeOptions();
              options.addArguments("start-maximized");
              WebDriver driver =  new ChromeDriver(options);
              driver.get("https://www.amazon.com");
              WebElement department = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@id='nav-link-shopall' and normalize-space()='Departments']")));
              new Actions(driver).moveToElement(department).perform();
          }
      }
      
    • 浏览器快照:

    【讨论】:

    • 如何获取列表的长度。我使用了代码: List e = driver.findElements(By.xpath("//span[@class='nav-line-2' and contains(.,'Departments')]")); int itemsCount = e.size(); System.out.println(itemsCount);
    • @squathub 恐怕你的问题是关于将鼠标悬停在亚马逊的下拉菜单上,这就是我的答案。如果您的要求发生了变化,您可以根据您的新要求提出新的要求吗? StackOverflow 志愿者很乐意为您提供帮助。
    • @squathub 如果这个/任何答案对您/对您有帮助,对未来的读者有帮助,请为答案投票。
    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多