我正在尝试在Google.com的前5页上打印所有结果链接的名称
情景是, 1)访问www.google.com并搜索内容。 2)在前5页打印所有结果链接的名称
我可以打印首页的所有结果链接,然后点击下一页链接。但第二页链接不打印。我认为原因可能是第二页中xpath的变化。如果是这样,我如何打印第2第3和第5页的所有链接。 请帮助我解决这个问题。
package com;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.firefox.internal.ProfilesIni;
public class Exercise2 {
static WebDriver d;
public static void main(String[] args) throws InterruptedException {
ProfilesIni prop = new ProfilesIni();
FirefoxProfile seleniumProfile = prop.getProfile(("Selenium"));
d = new FirefoxDriver();
d.manage().window().maximize();
d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
d.get("http://www.google.com");
Thread.sleep(5000);
d.findElement(By.name("q")).sendKeys("Selenium");
d.findElement(By.name("q")).sendKeys(Keys.ENTER);
Thread.sleep(5000);
//Print names of all result links on first page.
String part1 = "//div[@id='rso']/div[2]/div[";
String part2 = "]/div/h3/a";
for(int i=2;i<=5;i++){
String part3 = "//div[@id='navcnt']/table/tbody/tr/td[";
String part4 = "]";
int a = 1;
while(isElementPresent(part1+a+part2)){
String text = d.findElement(By.xpath(part1+a+part2)).getText();
System.out.println(text);
a++;
}
Thread.sleep(5000);
System.out.println("*************Next Page**********");
Thread.sleep(5000);
d.findElement(By.xpath(part3+i+part4)).click();
}
}
public static boolean isElementPresent(String xpathexp){
List<WebElement> allList = d.findElements(By.xpath(xpathexp));
//WebElement nextPages = d.findElement(By.xpath(nextPage1));
if(allList.size()==0)
{
return false;
}else{
return true;
}
}
}
答案 0 :(得分:0)
List<WebElements> links = driver.findElements(By.tagName("a"));
for(int i = 0 ; i < 5 ; i ++)
{
string firstLink = links[i].getAttribute("href");
}
答案 1 :(得分:0)
尝试以下代码。
▶ class Var
▷ def iv
▷ @iv ||= 42
▷ end
▷ end
▶ Var.new.instance_variables
#⇒ []
# the above is because instance variables are lazily instantiated
▶ v = Var.new
▶ v.iv
#⇒ 42
▶ v.instance_variables
#⇒ [ :@iv ]
}
如果有任何问题,请告诉我。