我想做一个简单的控制台应用程序,类似于搜索引擎。
它询问用户要搜索什么,在google上查找结果,然后用户可以键入“点击第一个/第二个/第三个链接(等等)”,然后应用程序自动单击该链接。
我试过使用Selenium,我可以开始搜索并找到结果,但我不知道如何实际单击链接。我也尝试过使用鼠标坐标,但代码对我来说太复杂了。
我还试图找到一种方法来提取前5个谷歌结果的链接,然后以某种方式点击它们。
总之,我已经找了好几个小时了,但我还没有找到任何东西。如果你们能帮我,那就太棒了!
下面是代码:
static void Main(string[] args)
{
Console.WriteLine("Search for:");
string command = Console.ReadLine();
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.google.com");
driver.Manage().Window.Maximize();
IWebElement searchInput = driver.FindElement(By.Id("lst-ib"));
searchInput.SendKeys(command);
searchInput.SendKeys(Keys.Enter);
}
发布于 2015-11-11 06:43:41
如果它是一个控制台应用程序,您将无法单击一个链接,因为页面将不会显示。您可以从搜索结果页面抓取链接,但在导航之后如何显示该页面?我想我不明白你项目的总体目标是什么。
如果你只想抓取谷歌搜索结果页面上的链接,你可以使用下面的代码。它将抓取页面上所有搜索结果的URL。然后,您可以在屏幕上显示多个链接,然后在用户选择链接之后导航(什么?)到所需的URL。
IWebElement searchInput = Driver.FindElement(By.Id("lst-ib"));
searchInput.SendKeys(command);
searchInput.SendKeys(Keys.Enter);
WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(5));
By linkLocator = By.CssSelector("cite._Rm");
wait.Until(ExpectedConditions.ElementToBeClickable(linkLocator));
IReadOnlyCollection<IWebElement> links = Driver.FindElements(linkLocator);
foreach (IWebElement link in links)
{
Console.WriteLine(link.Text);
}
https://stackoverflow.com/questions/33637875
复制相似问题