要求:转到过去3天的求职链接。 1)打印作业说明 2)点击下一个链接转到下一页,直到到达最后一页
问题:当我到达最后一页时,我正在使用try catch,因为找不到下一个链接的元素。使用此解决方案,它会停止脚本,通过查看JUNIT栏,您将不知道测试是通过还是失败。因为我使用退出,所以它是一个灰色栏。我怎样才能使这个代码变得更好,这样我就不必使用try catch并看到一个绿色条进行通过测试?
代码:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class QAJob {
@Test
public void jobSearch(){
WebDriver driver= new FirefoxDriver();
driver.get("https://www.indeed.com/jobs?as_and=qa+engineer&as_phr=&as_any=&as_not"
+ "=&as_ttl=&as_cmp=&jt=all&st=&salary=&radius=10&l=Bellevue%2C+WA&fromage=7&limit"
+ "=10&sort=date&psf=advsrch");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//code to scroll down to find the rest pages link
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("window.scrollBy(0,1000)", "");
// Find and print the number of pages for the search
List<WebElement> search_pages=driver.findElements(By.xpath("//div [contains(@class,'pagination')]//a"));
System.out.println("Number of pages found for this search " + search_pages.size());
while(search_pages.size()!=0){
List<WebElement> job_desc=driver.findElements(By.xpath("//div [contains(@id,'p')][contains(@class,'row')]"));
for(WebElement e:job_desc){
String str_job_desc=e.getText();
System.out.println(str_job_desc);
}
try
{
// closes the pop up that appears
driver.findElement(By.id("popover-x-button")).click();
}
catch (Exception e)
{
}
try
{
//click on next link to go to next page
driver.findElement(By.xpath("//span[contains(@class,'np')][contains(text(),'Next')]")).click();
//scroll down
JavascriptExecutor jse1 = (JavascriptExecutor) driver;
jse1.executeScript("window.scrollBy(0,1000)", "");
}
//when I get the exception(because no next link is available) exit.
catch (org.openqa.selenium.NoSuchElementException e)
{
System.exit(0);
}
}
}
}
提前感谢您的时间和建议。
答案 0 :(得分:1)
您实际上可以重复使用代码中使用的技巧来避免try-catch块
List<WebElement> popXButton=driver.findElements(By.id("popover-x-button"));
if (popXButton.size()>0){
driver.findElement(By.id("popover-x-button")).click();
}
同样延伸到下一个块
List<WebElement> nextVal=driver.findElements(By.xpath("//span[contains(@class,'np')][contains(text(),'Next')]"));
if(nextVal.size()>0){
driver.findElement(By.xpath("//span[contains(@class,'np')][contains(text(),'Next')]")).click();
}
else{
break;//exits while loop!
}