使用PhantomJS代替Selenium Firefox

时间:2016-01-25 19:56:25

标签: python firefox selenium

我正在使用Selenium Firefox驱动程序在Python中生成的简单测试。 我想让Firefox保持沉默,所以我使用了PhantomJS。 该代码适用于Firefox,但PhantomJS并非如此。

# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException

import unittest, time, re

class Webdriver(unittest.TestCase):
    def setUp(self):
        #self.driver = webdriver.Firefox()
        self.driver = webdriver.PhantomJS()
        self.driver.implicitly_wait(30)
        self.base_url = "https://www.google.fr/"
        self.verificationErrors = []
        self.accept_next_alert = True

    def test_webdriver(self):
        driver = self.driver
        driver.get(self.base_url + "/?gfe_rd=cr&ei=SuqkVv2gJ4_u8wfRjbnIBg&gws_rd=ssl")
        driver.find_element_by_id("lst-ib").clear()
        driver.find_element_by_id("lst-ib").send_keys("this is a test")

    def is_element_present(self, how, what):
        try: self.driver.find_element(by=how, value=what)
        except NoSuchElementException as e: return False
        return True

    def is_alert_present(self):
        try: self.driver.switch_to_alert()
        except NoAlertPresentException as e: return False
        return True

    def close_alert_and_get_its_text(self):
        try:
            alert = self.driver.switch_to_alert()
            alert_text = alert.text
            if self.accept_next_alert:
                alert.accept()
            else:
                alert.dismiss()
            return alert_text
        finally: self.accept_next_alert = True

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

这是我得到的错误:

E
======================================================================
ERROR: test_webdriver (__main__.Webdriver)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "webdriver.py", line 23, in test_webdriver
    driver.find_element_by_id("lst-ib").clear()
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 234, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 712, in find_element
    {'using': by, 'value': value})['value']
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 201, in execute
    self.error_handler.check_response(response)
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 188, in check_response
    raise exception_class(message, screen, stacktrace)
NoSuchElementException: Message: {"errorMessage":"Unable to find element with id 'lst-ib'","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Connection":"close","Content-Length":"87","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:35319","User-Agent":"Python-urllib/2.7"},"httpVersion":"1.1","method":"POST","post":"{\"using\": \"id\", \"sessionId\": \"d34495b0-c39c-11e5-84b8-adc96a3fa6c2\", \"value\": \"lst-ib\"}","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/d34495b0-c39c-11e5-84b8-adc96a3fa6c2/element"}}


----------------------------------------------------------------------
Ran 1 test in 33.627s

FAILED (errors=1)

修改

根据@alecxe的回复,向PhantomJS添加代理程序可以进行一些测试但是却失败了。

错误消息是:

Message:{  
   "errorMessage":"Element is not currently visible and may not be manipulated",
   "request":{  
      "headers":{  
         "Accept":"application/json",
         "Accept-Encoding":"identity",
         "Connection":"close",
         "Content-Length":"81",
         "Content-Type":"application/json;charset=UTF-8",
         "Host":"127.0.0.1:41594",
         "User-Agent":"Python-urllib/2.7"
      },
      "httpVersion":"1.1",
      "method":"POST",
      "post":"{\"sessionId\": \"074c7810-c3bf-11e5-beca-8f942aed378d\", \"id\": \":wdc:1453766104559\"}",
      "url":"/click",
      "urlParsed":{  
         "anchor":"",
         "query":"",
         "file":"click",
         "directory":"/",
         "path":"/click",
         "relative":"/click",
         "port":"",
         "host":"",
         "password":"",
         "user":"",
         "userInfo":"",
         "authority":"",
         "protocol":"",
         "source":"/click",
         "queryKey":{  

         },
         "chunks":[  
            "click"
         ]
      },
      "urlOriginal":"/session/074c7810-c3bf-11e5-beca-8f942aed378d/element/%3Awdc%3A1453766104559/click"
   }
}

1 个答案:

答案 0 :(得分:2)

假装不是PhantomJS使用自定义User-Agent标题:

dcap = dict(webdriver.DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
self.driver = webdriver.PhantomJS(desired_capabilities=dcap)

为我工作。

您还可以通过添加fluent explicit waits来改进测试。例如,等待元素可见

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.ID, "lst-ib"))
)
element.clear()
element.send_keys("this is a test")