在 Selenium 中需要验证搜索结果 [关闭]
Posted
技术标签:
【中文标题】在 Selenium 中需要验证搜索结果 [关闭]【英文标题】:In Selenium need to validate search result [closed] 【发布时间】:2022-01-12 11:46:20 【问题描述】:我的 excel 中有公司列表我想用 Java 编写一个脚本来验证将出现在我们网站的搜索列表中的公司列表,搜索中不存在的公司应该失败并且存在的公司得到验证 我应该使用什么逻辑
【问题讨论】:
您需要添加您遇到的问题以及您尝试过的内容 【参考方案1】:假设 XLSX 列表如下所示:
从https://opencorporates.com/ 的搜索中加载一些公司名称的代码示例:
package selenium;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class MohitNarwal extends WebDriverSetup
public static void main(String[] args) throws IOException
List<String> companyNamesFromWeb = new ArrayList<String>();
List<String> companyNamesFromFile = new ArrayList<String>();
WebDriver driver = startChromeDriver();
driver.get("https://opencorporates.com/");
WebElement searchInput = driver.findElement(By.name("q"));
searchInput.click();
searchInput.sendKeys("bank");
WebElement searchButton = driver.findElement(By.className("oc-home-search_button"));
searchButton.click();
WebElement ulCompanies = driver.findElement(By.id("companies"));
List<WebElement> results = ulCompanies.findElements(By.tagName("li"));
for (WebElement result: results)
List<WebElement> aTags = result.findElements(By.tagName("a"));
if (aTags.size() > 1)
String companyName = aTags.get(1).getText().replace("\"", "").trim();
companyNamesFromWeb.add(companyName);
driver.quit();
File file = new File("C:\\companyList.xlsx");
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook myWorkBook = new XSSFWorkbook(fis);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
int rowCount = mySheet.getPhysicalNumberOfRows();
for (int i = 1; i < rowCount; i++)
companyNamesFromFile.add(mySheet.getRow(i).getCell(0).getStringCellValue());
myWorkBook.close();
for (String companyNameFromFile: companyNamesFromFile)
if (!companyNamesFromWeb.contains(companyNameFromFile))
System.out.println("Company name: " + companyNameFromFile + " not found in search result.");
输出:
Starting ChromeDriver 96.0.4664.45 (76e4c1bb2ab4671b8beba3444e61c0f17584b2fc-refs/branch-heads/4664@#947) on port 20317
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Pro 07, 2021 3:24:47 ODP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
Company name: Apple Computers inc. not found in search result.
但这只是一个例子。如果您使用某种测试方法,您可以根据需要调整代码。对于JUnit
,您可以使用https://mkyong.com/unittest/junit-how-to-test-a-list/。
【讨论】:
以上是关于在 Selenium 中需要验证搜索结果 [关闭]的主要内容,如果未能解决你的问题,请参考以下文章