我的要求是,我想在谷歌和结果页面上搜索文本,找到所有存在该文本的链接,然后点击该链接。 步骤中的要求说明: Step1)打开谷歌主页 step2)搜索关键字 步骤3)在结果页面上打印包含搜索关键字的所有链接 step4)点击包含搜索关键字的链接
所以想知道是否有任何方法可以通过selenium或任何其他工具实现这一目标,详情说明表示赞赏
提前致谢
答案 0 :(得分:1)
这是一个使用Selenium WebDriver的C#控制台应用程序。
using System;
using System.Collections.Generic;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
IWebDriver driver = new FirefoxDriver();
// The keyword you would like to search for
string keyword = "stack overflow";
// Step 1
driver.Url = "http://www.google.com/";
// Step 2
IWebElement input = driver.FindElement(By.Id("lst-ib"));
input.SendKeys(keyword);
input.Submit();
// Wait for page to load
Thread.Sleep(3000);
// Fill a list with the resulting links
List<string> results = new List<string>();
ICollection<IWebElement> searchResults = driver.FindElements(By.XPath("//ol[@id='rso']/li/div/h3/a"));
foreach (IWebElement resultLink in searchResults)
{
string link = resultLink.GetAttribute("href");
results.Add(link);
}
// Output each link and click on each link
foreach (string link in results)
{
// Step 3
Console.WriteLine(link);
// Step 4
driver.Url = link;
}
Console.ReadLine();
}
}
}
答案 1 :(得分:0)
此代码将在Google中搜索文本并收集结果页面上的所有链接!
package com.example.tests;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.builder.ToStringStyle;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.thoughtworks.selenium.*;
public class CopyOfsource {
private static WebDriver driver;
public static void main(String[] args) throws IOException {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.print("***********test**************");
driver.get("http://www.google.co.in/#hl=en&q=test&oq=test&aq=f&aqi=g10&aql=1&gs_sm=e&gs_upl=1452727l1453164l0l1453839l7l5l0l0l0l0l278l1194l2-
5l5l0&bav=on.2,or.r_gc.r_pw.,cf.osb&fp=2bcac73b2935e785&biw=1366&bih=643");
List<WebElement> element = driver.findElements(By.xpath("//ol[@id='rso']/li/div/h3/a"));
List<String> results = new ArrayList<String>();
int num=element.size();
System.out.println("***************Report Created is in Location "+ num + "/n");
for(int i=0;i<num;i++)
{
WebElement resultlink = element.get(i);
String link = resultlink.getAttribute("href");
results.add(link);
System.out.println("***************Report Created is in Location : " + link);
}
driver.close();
}}