这是我的测试类,包含所有代码行。我认为问题出在 xpath 中,因为它无法找到元素。
package practice;
import java.util.List;
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;
public class selPractice {
public static void main(String[] args) throws InterruptedException
{
String key="webdriver.chrome.driver";
String value="./software/chromedriver.exe";
System.setProperty(key, value);
WebDriver driver=new ChromeDriver();
driver.get("https://www.google.com");
//to automate auto suggestion
driver.findElement(By.xpath("//input[@title='Search']")).sendKeys("motogp");
List<WebElement>motolist=driver.findElements(By.xpath("//ul[@role='listbox]
//li/descendant::div[@class='sbl1']"));
Thread.sleep(2000);
int count=motolist.size();
System.out.println(count);
for(WebElement list:motolist)
{
String text=list.getText();
System.out.println(text);
}
}
}
要提取自动建议来自搜索框 on 谷歌主页 https://www.google.com/你必须诱导WebDriver等待为了所有元素的可见性您可以使用以下解决方案:
-
代码块:
import java.util.List;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Google_Auto_Suggestions {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("start-maximized");
options.addArguments("disable-infobars");
options.addArguments("--disable-extensions");
WebDriver driver = new ChromeDriver(options);
driver.get("http://www.google.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.name("q"))).sendKeys("motogp");
List<WebElement> motolist = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElementsLocatedBy(By.xpath("//form[@action='/search' and @role='search']//ul[@role='listbox']//li//span")));
for(WebElement list:motolist)
{
String text=list.getText();
System.out.println(text);
}
}
}
-
控制台输出:
Only local connections are allowed.
Dec 04, 2018 6:14:51 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
motogp
motogp 2018
motogp live
motogp results
motogp game
motogp news
motogp bikes
motogp race
motogp wiki
motogp schedule
浏览器快照:
在这里您可以找到相关讨论Python 硒测试。如何从 Google 主页搜索框中提取自动建议? https://stackoverflow.com/questions/49325855/python-selenium-testing-how-can-i-extract-the-auto-suggestions-from-search-box/49333769#49333769
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)