Как бороться с поиском, который не дает результатов на веб-странице? - PullRequest
0 голосов
/ 03 июля 2018

Несколько дней назад я написал программу с некоторой помощью от нескольких других участников Stack Overflow, и теперь у меня появился новый вопрос о функциональности.

Так вот мой код:

// importing a bunch of packages

public class webSearch  {
public webSearch() {

}

public WebDriver driver = new ChromeDriver();

public void openTestSite() {
    //driver.navigate().to(the URL for the website);
    driver.get("https://wonef.fr/try/");
    driver.manage().window().maximize();
    //Explicit wait is added after the Page load
    WebDriverWait wait=new WebDriverWait(driver,20);
    wait.until(ExpectedConditions.titleContains("WoNeF"));
} 

public void enter(String word) {

    WebElement query_editbox =
            driver.findElement(By.id("query"));
    query_editbox.sendKeys(word);
    //AutoComplete is happening even after sending the Enter Key.
    // So, Value needs to be selected from the autocomplete
    WebDriverWait wait=new WebDriverWait(driver,20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='autocomplete']/div")));
    List<WebElement> matchedList=driver.findElements(By.xpath("//div[@class='autocomplete']/div"));

   // System.out.println(matchedList.size());
    for(WebElement element : matchedList){
        if(element.getText().equalsIgnoreCase(word)){
            element.click();
        }
    }
    query_editbox.sendKeys(Keys.RETURN);
}

public void getText(String name) throws IOException  {
    WebDriverWait wait=new WebDriverWait(driver,20);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='mid']/div")));
    WebElement result=driver.findElement(By.id("mid"));
    Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name), "utf-8"));
    writer.write(result.getText());
    writer.close();
}

}

Он в основном открывает веб-сайт, вводит слово, нажимает клавишу ввода, а затем сохраняет все, что возвращается в текстовый файл.

Мой вопрос заключается в том, как мне поступить с программой, когда слово вводится, но в поиске нет ни одного нажатия. Это всегда вызывает следующую ошибку в моем коде:

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //div[@class='autocomplete']/div (tried for 20 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:81)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:271)
    at src.webSearch.enter(webSearch.java:43)
    at src.Engine.main(Engine.java:58)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //div[@class='autocomplete']/div
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:14.902Z'
System info: host: 'my-MacBook-Air.local', ip: 'fe80:0:0:0:a6d1:8cff:fece:5dae%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_171'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.ExpectedConditions.lambda$findElement$0(ExpectedConditions.java:896)
    at java.util.Optional.orElseThrow(Optional.java:290)
    at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:895)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:44)
    at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:206)
    at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:202)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:248)
... 2 more

Новая ошибка:

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.xpath: //div[@id='mid']/div (tried for 20 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:81)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:271)
    at src.webSearch.getText(webSearch.java:62)
    at src.Engine.main(Engine.java:57)
Caused by: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.xpath: //div[@id='mid']/div
For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.13.0', revision: '2f0d292', time: '2018-06-25T15:32:14.902Z'
System info: host: 'my-MacBook-Air.local', ip: 'fe80:0:0:0:a6d1:8cff:fece:5dae%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_171'
Driver info: driver.version: unknown
    at org.openqa.selenium.support.ui.ExpectedConditions.lambda$findElement$0(ExpectedConditions.java:896)
    at java.util.Optional.orElseThrow(Optional.java:290)
    at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:895)
    at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:44)
    at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:206)
    at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:202)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:248)
    ... 2 more

Новые редакции! T он следит за кодом, который у меня был давно.

import java.io.BufferedWriter;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
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.WebDriverWait;
import org.openqa.selenium.remote.RemoteWebDriver;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.lang.ClassLoader;

import com.sun.corba.se.impl.orbutil.threadpool.TimeoutException;



public class webSearch  {

    public webSearch() {

    }

    public WebDriver driver = new ChromeDriver()
            ;

    public void openTestSite() {

    //driver.navigate().to(the URL for the website);
    driver.get("https://wonef.fr/try/");
    driver.manage().window().maximize();
    //Explicit wait is added after the Page load
    WebDriverWait wait=new WebDriverWait(driver,20);
    wait.until(ExpectedConditions.titleContains("WoNeF"));
}


    public void enter(String word) {

        WebElement query_editbox =
                driver.findElement(By.id("query"));
        System.out.println("Hello");
        query_editbox.sendKeys(word);
        System.out.println("Hello");
        //AutoComplete is happening even after sending the Enter Key.
        // So, Value needs to be selected from the autocomplete
        WebDriverWait wait=new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='autocomplete']/div")));
        List<WebElement> matchedList=driver.findElements(By.xpath("//div[@class='autocomplete']/div"));

        System.out.println(matchedList.size());
        for(WebElement element : matchedList){
            if(element.getText().equalsIgnoreCase(word)){
                element.click();
            }
        }
        //query_editbox.sendKeys(Keys.RETURN);
    }

    public void getText()  {
        WebDriverWait wait=new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='mid']/div")));
        WebElement result=driver.findElement(By.id("mid"));
        System.out.println(result.getText());
    }

    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "/Users/shivamsinghal/Documents/chromedriver.exe");        
        System.out.println("Hello");

        webSearch webSrcapper = new webSearch();
        webSrcapper.openTestSite();
        webSrcapper.enter("avoir");
        webSrcapper.getText();
        System.out.println("Hello");
    }
}

Вот новая ошибка, которую я получаю:

Command duration or timeout: 0 milliseconds
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:48'
System info: host: 'ny-MacBook-Air.local', ip: 'fe80:0:0:0:a6d1:8cff:fece:5dae%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.6', java.version: '1.8.0_171'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.40.565386 (45a059dc425e08..., userDataDir: /var/folders/pq/hvxfhc1s22x...}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: MAC, platformName: MAC, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 71.0.3578.98, webStorageEnabled: true}
Session ID: cbff8e41d512f5970d24017a4911ced0
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:609)
    at org.openqa.selenium.remote.RemoteWebDriver$RemoteWebDriverOptions$RemoteWindow.maximize(RemoteWebDriver.java:837)
    at webSearch.openTestSite(webSearch.java:41)
    at webSearch.main(webSearch.java:82)

Ответы [ 2 ]

0 голосов
/ 03 июля 2018

Когда вы ввели какое-то недоступное слово, автозаполнение не происходит и, следовательно, TimeoutException выбрасывает. Вам нужно обработать это исключение, используя try catch block. Так что ваше выполнение будет продолжено без каких-либо исключений. Если вам нужно добавить логику, когда автозаполнение не происходит, вы можете обработать эту логику в блоке catch.

Если автозаполнение не отображается в течение 20 секунд, то можно предположить, что введенное значение недопустимо.

Пожалуйста, найдите измененный код:

введите метод :

public void enter(String word) {

    WebElement query_editbox =
            driver.findElement(By.id("query"));
    query_editbox.clear();
    query_editbox.sendKeys(word);

    try{
        //AutoComplete is happening even after sending the Enter Key.
        // So, Value needs to be selected from the autocomplete
        WebDriverWait wait=new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='autocomplete']/div")));
        List<WebElement> matchedList=driver.findElements(By.xpath("//div[@class='autocomplete']/div"));

       // System.out.println(matchedList.size());
        for(WebElement element : matchedList){
            if(element.getText().equalsIgnoreCase(word)){
                element.click();
            }
        }   

    }catch (TimeoutException e){
            System.out.println("Invalid Word is entered");

    }

    query_editbox.sendKeys(Keys.RETURN);
}

Редактировать: К адресу следующего вопроса

  1. Я добавил действие clear в методе enter перед вводом слова. Вы можете ввести цикл for в свой метод main для выполнения с другими словами

    String[] input={};
    
    for(int i=0;i<input.length;i++){
        webSrcapper.enter(input[i]);
        webSrcapper.getText();
    }
    

Образец со списком массивов:

    ArrayList<String> list=new ArrayList<>();

    list.add("Word1");
    list.add("Word2");
    list.add("Word3");

    for(int i=0;i<input.length;i++){
        webSrcapper.enter(list.get(i));
        webSrcapper.getText();
    }
  1. Вы можете выполнить свой тест, не открывая браузер, и это можно сделать с помощью любого из безголовых браузеров. Я бы предложил использовать браузер Chrome в качестве браузера без заголовка Chrome, включив параметры, указанные ниже.

Вам необходимо изменить класс webSearch, как показано ниже

public class webSearch  {
    public WebDriver driver;

    public webSearch() {
        ChromeOptions options = new ChromeOptions();
        options.addArguments("headless");
        driver=new ChromeDriver(options);
    }

Метод getText:

public void getText(String name) throws IOException  {

    try{
        WebDriverWait wait=new WebDriverWait(driver,20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='mid']/div")));
        WebElement result=driver.findElement(By.id("mid"));
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(name), "utf-8"));
        writer.write(result.getText());
        writer.close();
    }catch (TimeoutException e){
            System.out.println("No Result is found for the requested word");

    }

}
0 голосов
/ 03 июля 2018

Вы можете выбрать желаемый вариант, используя код ниже:

        WebElement query_editbox = driver.findElement(By.id("query"));
        query_editbox.sendKeys("bad");
        String wordToBeSelected = "badge";
        selectOptionFromDropdown(driver, wordToBeSelected);

    private static void selectOptionFromDropdown(WebDriver driver, String wordToBeSelected) {
        WebDriverWait wait=new WebDriverWait(driver,25);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".autocomplete div")));

        List<WebElement> dropdownList = driver.findElements(By.cssSelector(".autocomplete div"));
        WebElement desiredElement = dropdownList.stream()
                                                .filter(element -> element.getAttribute("title").equals(wordToBeSelected))
                                                .findFirst().get();
        desiredElement.click();
    }

Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...