Sure, here’s the translation: “java selenium xpath relative”

huangapple go评论67阅读模式
英文:

java selenium xpath relative

问题

我需要编写一个程序,该程序将使用XPath相对路径在Allegro上搜索轻型无人机。

使用Selenium Webdriver,在浏览器中打开Allegro门户,然后将产品类别切换到Electronics,并在搜索框中输入"Mavic mini"。

我正在使用Java和IntelliJ进行操作,我已经到达了打开网站的地步,我点击了警告框以关闭它,并将"Elektronika"输入类别字段。我无法编写应该输入"mavic mini"的代码部分,以下是整个代码的样子:

```java
import org.openqa.selenium.Alert;
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.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AllegroTestingApp {
    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "c:\\selenium-drivers\\chrome\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.allegro.pl");

        WebElement categoryCombo = driver.findElement(By.xpath("//div//div//select"));
        Select categorySelect = new Select(categoryCombo);
        categorySelect.selectByIndex(3);
        driver.manage().window().maximize();
        driver.findElement(By.xpath("/html/body/div[2]/div[8]/div/div[2]/div/div[2]/button[2]")).click();
        Alert simpleAlert = driver.switchTo().alert();
        simpleAlert.accept();
        WebElement inputField =
                driver.findElement(By.xpath("//INPUT[@type='search']/self::INPUT"));
        inputField.sendKeys("mavic mini");
        inputField.submit();
    }
}

<details>
<summary>英文:</summary>

I have to write a program that will search for light drones on Allegro. (using XPath relative)

Using Selenium Webdriver, open the Allegro portal in your browser, then switch the product category to Electronics and enter &quot;Mavic mini&quot; in the search field.

I&#39;m using Java and IntelliJ for that, I got to the point when I&#39;m going to the website, I click on the alert so it&#39;s closed and I put &quot;Elektronika&quot; into the category field. I can&#39;t write that part of code where it should type &quot;mavic mini&quot;, here&#39;s how it all looks like;
import org.openqa.selenium.Alert; 
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.support.ui.Select; 
import org.openqa.selenium.support.ui.WebDriverWait;


public class AllegroTestingApp {
     public static void main(String[] args) {

     System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;c:\\selenium-drivers\\chrome\\chromedriver.exe&quot;);
     WebDriver driver = new ChromeDriver();
     driver.get(&quot;https://www.allegro.pl&quot;);

     WebElement categoryCombo = driver.findElement(By.xpath(&quot;//div//div//select&quot;));
     Select categorySelect = new Select(categoryCombo);
     categorySelect.selectByIndex(3);
     driver.manage().window().maximize();
     driver.findElement(By.xpath(&quot;/html/body/div[2]
    /div[8]/div/div[2]/div/div[2]/button[2]&quot;)).click();
    Alert simpleAlert = driver.switchTo().alert();
    simpleAlert.accept();    
    WebElement inputField = 
    driver.findElement(By.xpath(&quot;//INPUT[@type=&#39;search&#39;]/self::INPUT&quot;));
    inputField.sendKeys(&quot;mavic mini&quot;);
    inputField.submit();

}

Please help!

</details>


# 答案1
**得分**: 1

我看到问题中提供的代码是有效的,只需将以下行注释掉。似乎在该页面不再有警告。

    // Alert simpleAlert = driver.switchTo().alert();
    // simpleAlert.accept();

<details>
<summary>英文:</summary>

I see the code given in question is working by just commenting below lines. Seems like no alert anymore in that page.

    Alert simpleAlert = driver.switchTo().alert();
    simpleAlert.accept(); 

</details>



# 答案2
**得分**: 0

几点反馈事项:
1. 你针对 `categoryCombo` 的定位器过于宽泛/通用,应该在可能的情况下更具体。始终寻找ID、名称或页面上唯一的其他属性。在这种情况下,它具有一个唯一的 `aria-label`,我们可以使用它来创建一个唯一的定位器,`By.cssSelector(&quot;select[aria-label=&#39;Kategoria i opcje wyszukiwania&#39;]&quot;)`

2. 与其按索引选择,你应该选择发送你要查找的实际值,例如 "Elektronika"。这样可以使代码更具可读性,如果类别更改(更改索引),你的代码仍然可以工作。为此,你可以使用 `Select.selectByVisibleText()`。

3. 你的代码的下一部分我不理解。你点击了一个按钮,然后接受一个JS弹窗?我没有看到那部分,所以不确定你在那里看到了什么,或者你是在尝试在设置下拉列表之前接受/关闭初始弹窗吗?如果是这样,你的代码顺序有问题。

4. 你的搜索框定位器虽然有效,但不够具体,并且有一些不相关的部分,例如 "&quot;.../self::INPUT&quot;" 部分是不必要的。如同我在第一点中所述,你要尽可能具体地使用ID、名称等来定位。在这种情况下,搜索框有一个名称,所以我使用了它,`By.cssSelector(&quot;input[name=&#39;string&#39;]&quot;)`

5. 大多数情况下,搜索网站上的一个项目的人最终都会搜索另一个项目。在这种情况下,最好将与搜索相关的代码封装到一个方法中。我创建了 `SelectCategory()` 方法,它接受类别名称并进行设置。我还创建了 `Search()` 方法,它接受类别名称和搜索字符串,并执行完整的搜索。你可以在下面的代码中看到它们两者。

6. 因为我将一些代码移到不同的方法中,我将驱动程序实例变量移到了类的顶部,这样你不必将它传递到每个方法中。

以下是我修改后的工作代码:

```java
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AllegroTestingApp {
    static WebDriver driver;

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "c:\\selenium-drivers\\chrome\\chromedriver.exe");
        driver = new ChromeDriver();
        driver.manage().window().maximize();

        String url = "https://www.allegro.pl";
        driver.get(url);

        new WebDriverWait(driver, 10)
            .until(ExpectedConditions.elementToBeClickable(By.cssSelector("img[alt=&#39;zamknij&#39;]")))
            .click();

        Search("Elektronika", "mavic mini");

        driver.quit();
    }

    public static void Search(String categoryName, String searchString) {
        SelectCategory(categoryName);
        WebElement searchBox = driver.findElement(By.cssSelector("input[name=&#39;string&#39;]"));
        searchBox.sendKeys(searchString);
        searchBox.submit();
    }

    public static void SelectCategory(String categoryName) {
        By categoryDropdownLocator = By.cssSelector("select[aria-label=&#39;Kategoria i opcje wyszukiwania&#39;]");
        new Select(driver.findElement(categoryDropdownLocator)).selectByVisibleText(categoryName);
    }
}

注意:由于你要求仅返回翻译后的部分,上述代码是经过翻译的版本,与你提供的原始代码是等价的。

英文:

A few feedback items:

  1. Your locator for categoryCombo is very broad/generic and should be more specific when possible. Always look for an ID, a name, or some other attribute that is unique on the page. In this case, it has a unique aria-label that we can use to make a unique locator, By.cssSelector(&quot;select[aria-label=&#39;Kategoria i opcje wyszukiwania&#39;]&quot;)

  2. Rather than select by index, you should choose to send the actual value you are looking for, e.g. "Elektronika". That makes it much more readable and if the categories change (which changes the indices), your code will still work. For this you can use Select.selectByVisibleText().

  3. The next part of your code I don't understand. You are clicking a button and then accepting a JS alert? I'm not seeing that so I'm not sure what you are seeing there or if you were trying to accept/close the initial popup before setting the dropdown? If so, your code is out of order.

  4. Your locator for the search box was working but was not specific and had some irrelevant parts, e.g. the ".../self::INPUT" part is not necessary. As in my first point, you want to make your locator as specific as possible using ID, name, etc. In this case, the search box has a name so I used it, By.cssSelector(&quot;input[name=&#39;string&#39;]&quot;).

  5. Most of the time, people that search for one item on a site want to eventually search for another item. In that case, it's best to package up your search related code into a method. I created SelectCategory() that takes in the name of a category and sets it. I also created Search() which takes in the category name and the search string and does the complete search. You can see them both in the code below.

  6. Because I moved some code into different methods, I moved the driver instance variable to the top of the class so that you don't have to pass it into each method.

Here's my working code:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;

public class AllegroTestingApp
{    
    static WebDriver driver;

    public static void main(String[] args)
    {
        System.setProperty(&quot;webdriver.chrome.driver&quot;, &quot;c:\\selenium-drivers\\chrome\\chromedriver.exe&quot;);
        driver = new ChromeDriver();
        driver.manage().window().maximize();

        String url = &quot;https://www.allegro.pl&quot;;
        driver.get(url);

        // wait for popup and close
        new WebDriverWait(driver, 10).until(ExpectedConditions.elementToBeClickable(By.cssSelector(&quot;img[alt=&#39;zamknij&#39;]&quot;))).click();

        Search(&quot;Elektronika&quot;, &quot;mavic mini&quot;);

        driver.quit();
    }

    public static void Search(String categoryName, String searchString)
    {
        SelectCategory(categoryName);
        WebElement searchBox = driver.findElement(By.cssSelector(&quot;input[name=&#39;string&#39;]&quot;));
        searchBox.sendKeys(searchString);
        searchBox.submit();
    }

    public static void SelectCategory(String categoryName)
    {
        By categoryDropdownLocator = By.cssSelector(&quot;select[aria-label=&#39;Kategoria i opcje wyszukiwania&#39;]&quot;);
        new Select(driver.findElement(categoryDropdownLocator)).selectByVisibleText(categoryName);
    }
}

答案3

得分: 0

请尝试以下代码,它会有效:

driver.get("https://www.allegro.pl");
WebElement categoryCombo = driver.findElement(By.xpath("//div//div//select"));
Select categorySelect = new Select(categoryCombo);
categorySelect.selectByIndex(3);
driver.manage().window().maximize();
driver.findElement(By.xpath("/html/body/div[2]/div[8]/div/div[2]/div/div[2]/button[2]")).click(); 
WebElement inputField = driver.findElement(By.xpath("//input[@name='string']"));
inputField.sendKeys("mavic mini");
inputField.submit();
英文:

Try this code it will work:

driver.get(&quot;https://www.allegro.pl&quot;);
        WebElement categoryCombo = driver.findElement(By.xpath(&quot;//div//div//select&quot;));
        Select categorySelect = new Select(categoryCombo);
        categorySelect.selectByIndex(3);
        driver.manage().window().maximize();
        driver.findElement(By.xpath(&quot;/html/body/div[2]/div[8]/div/div[2]/div/div[2]/button[2]&quot;)).click(); 
       WebElement inputField =driver.findElement(By.xpath(&quot;//input[@name=&#39;string&#39;]&quot;));
       inputField.sendKeys(&quot;mavic mini&quot;);
       inputField.submit();

huangapple
  • 本文由 发表于 2020年10月6日 00:57:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/64213035.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定