我尝试制作隐藏的FirefoxDriver。根据我的研究,我必须使用PhantomJSDriver,但是当我使用PhantomJSDriver driver.FindElement语句不再起作用。
var options = new PhantomJSOptions(); options.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36"); PhantomJSOptions p = new PhantomJSOptions(); var service = PhantomJSDriverService.CreateDefaultService(); service.SslProtocol = "any"; service.ProxyType = "http"; service.WebSecurity = false; service.IgnoreSslErrors = true; var driver = new PhantomJSDriver(service, options); driver.Navigate().GoToUrl("https://www.google.com.tr/"); Thread.Sleep(5000); driver.FindElement(By.XPath("//*[@id='lst-ib']")).SendKeys("edd"); string s = driver.Url; Console.WriteLine(s);
错误信息:
An unhandled exception of type ‘OpenQA.Selenium.NoSuchElementException’ occurred in WebDriver.dll
Additional information: {“errorMessage”:”Unable to find element with xpath ‘//[@id=’_fZl’]/span/svg/path’“,”request”:{“headers”:{“Accept”:”application/json, image/png”,”Connection”:”Close”,”Content-Length”:”57”,”Content-Type”:”application/json;charset=utf-8”,”Host”:”localhost:50454”},”httpVersion”:”1.1”,”method”:”POST”,”post”:”{"using":"xpath","value":"//[@id=’_fZl’]/span/svg/path"}”,”url”:”/element”,”urlParsed”:{“anchor”:”“,”query”:”“,”file”:”element”,”directory”:”/”,”path”:”/element”,”relative”:”/element”,”port”:”“,”host”:”“,”password”:”“,”user”:”“,”userInfo”:”“,”authority”:”“,”protocol”:”“,”source”:”/element”,”queryKey”:{},”chunks”:[“element”]},”urlOriginal”:”/session/feab13f0-720f-11e7-80b3-452aee308158/element”}}
还有其他隐藏FirefoxDriver的方法吗?请问你能帮帮我吗?
我解决了 首先,我们可以通过以下代码使用PhantomJS而不显示其控制台:
IWebDriver driver; var driverService = PhantomJSDriverService.CreateDefaultService(); driverService.HideCommandPromptWindow = true; driver = new PhantomJSDriver(driverService);
其次是我提到的错误。Google为浏览器返回了不同的HTML页面,因此PhantomJS浏览器中的Id或Xpath与打开Firefox时导出的ID或Xpath不同。当我使用
string html=driver.PageSource;
要知道正确的XPath或Id,findElement函数运行良好。
例如:对于Google网站结果,FirefoxDriver中第一个链接的XPath是
"//*[@id='rso']/div/div/div[1]/div/div/h3/a"
PhantomJSDriver中第一个链接的XPath是
"//*[@id='ires']//ol/div[1]/h3/a"