How to hide FirefoxDriver (using Selenium) without findElement function error in PhantomDriver(headless browser)?

前端 未结 3 703
Happy的楠姐
Happy的楠姐 2021-01-16 11:09

I try to make hidden FirefoxDriver. According to my research I must use PhantomJSDriver but when I use PhantomJSDriver driver.FindElement statement no longer does not work.<

相关标签:
3条回答
  • 2021-01-16 11:26

    There is no way to hide FirefoxDriver per se. You could run it on a virtual machine and minimize the vm window but that's not practical for most people.

    Let's take a look at your real problem though. It looks like Google is assigning the id of the search box with js to prevent scraping since it's against their terms of service.

    You have a couple options here:

    1) locate the element using the name 'q' since it's named that regardless of phantomjs or firefox.

    2) just go directly to the search results page: https://www.google.com.tr/search?q=edd

    0 讨论(0)
  • 2021-01-16 11:29

    Since version 55+ for Linux and 56+ for Windows & OSX, Firefox supports the -headless command line option. It shall be used like this:

    o = selenium.webdriver.FirefoxOptions()
    o.set_headless()
    driver=selenium.webdriver.Firefox(options=o)
    

    The corresponding code in C# would be:

    var o = new FirefoxOptions()
    o.AddArgument('-headless')
    var driver = new FirefoxDriver(o)
    

    Because the .NET wrapper doesn't support the .headless property.

    0 讨论(0)
  • 2021-01-16 11:43

    I solved it. First of all We can use PhantomJS without showing its console by this code:

    IWebDriver driver; 
    var driverService = PhantomJSDriverService.CreateDefaultService();
    driverService.HideCommandPromptWindow = true;
    driver = new PhantomJSDriver(driverService);
    

    Second for the error that I mentioned. Google return different HTML pages for browsers so the Id or Xpath in PhantomJS browser will be different from that I export it when I was opening Firefox. When I used

    string html=driver.PageSource;
    

    to know what the correct XPath or Id, findElement functiom is working well.

    For example: For the Google site results The first link's XPath in FirefoxDriver is

    "//*[@id='rso']/div/div/div[1]/div/div/h3/a"
    

    The first link's XPath in PhantomJSDriver is

    "//*[@id='ires']//ol/div[1]/h3/a"
    
    0 讨论(0)
提交回复
热议问题