Python中的Selenium send_keys卡住了

3

我正在编写 "Python测试驱动开发" 中的示例,更具体地说是第一个功能测试。但由于某种奇怪的原因,send_keys 无法正常工作。这就是我现在正在尝试的 - 顺便说一下,我已经将隐式等待改为显式等待了!

    inputbox = self.browser.find_element_by_id('id_new_item')
    self.assertEqual( # This passes, it's here just for completeness
        inputbox.get_attribute('placeholder'),
        'Enter a To-Do item'
    )
    inputbox.send_keys('Buy peacock feathers')
    inputbox.send_keys(Keys.ENTER) # Everything okay up to here
    WebDriverWait(self.browser, 10).until(
        EC.text_to_be_present_in_element((By.CSS_SELECTOR, "table#id_list_table tr td"), "Buy peacock feathers")
    )
    table = self.browser.find_element_by_id('id_list_table')

    rows = table.find_elements_by_tag_name('tr')        
    self.assertIn('1: Buy peacock feathers', [row.text for row in rows])

    inputbox1 = self.browser.find_element_by_id('id_new_item') # Changed the variable only to test if it would hang too - and it does
    inputbox1.send_keys('Use peacock feathers to make a fly')
    inputbox1.send_keys(Keys.ENTER) # This hangs
    self.fail()
    WebDriverWait(self.browser, 10).until(
        EC.text_to_be_present_in_element((By.CSS_SELECTOR, "table#id_list_table tr td"), "Use peacock feathers to make a fly")
    )

它从未达到self.fail()。我尝试将其移至上一行,测试失败,就像应该的那样。但是inputbox1.send_keys(Keys.ENTER)从不起作用,当我看到浏览器运行测试时,inputbox1.send_keys('Use peacock feathers to make a fly')从不在输入框中写入“使用孔雀羽毛制作飞行器”。发生了什么?我正在使用最新的Selenium(我想是这样,我几天前下载了它刚刚检查,我确实有最新版本),Python和Django版本,在我的笔记本电脑上打开Firefox Developer Edition。谢谢。
编辑:我尝试禁用Firefox中的多进程,但结果没有改变-尝试写入并按回车键时仍然挂起。

另外,您使用的是哪个Selenium和Firefox版本? - alecxe
刚刚做了那个,输出结果一样。Firefox开发者版是46.0a2版本,Selenium是2.52.0版本。 - Carlos Vergara
好的,我认为可能是Firefox版本太新了,不适用于这个Selenium版本。尝试将Firefox降级到最新的稳定版本。请告诉我,谢谢。 - alecxe
开发者版通常不太稳定。我会尝试使用普通的Firefox来执行。 - Carlos Vergara
1
您也可以尝试使用Chrome浏览器,以便我们可以确定这是否是Firefox特定的问题。 - alecxe
显示剩余2条评论
2个回答

1
奇怪的是,我无法在Ubuntu shell中运行任何东西,但它可以通过Jupyter Notebook上的IPython从完全相同的服务器运行。

我不得不在代码中添加虚拟显示器,以使其作为.py脚本从shell运行...

如果有人面临类似问题,这是我在脚本中添加的代码行,发送键开始工作而没有问题。似乎即使我为我的chrome driver保留了无头开关,仍然需要它。

from pyvirtualdisplay import Display

# Set screen resolution to 1366 x 768. This is needed 
# to run in the shell. Seems fine in iPython.
display = Display(visible=0, size=(1366, 768))
display.start()

1

感谢alexce的帮助!

我在我的测试类中进行了以下更改:

from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

def setUp(self):
    binary = FirefoxBinary('C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe')
    self.browser = webdriver.Firefox(firefox_binary=binary)

问题是什么?我使用的是Firefox开发者版,显然Selenium并不完全支持它。因此,我强制Selenium加载我的常规Firefox,现在不会再挂起了!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接