Python - Selenium Web Driver error - self._driver.execute - AttributeError: 'unicode' object has no attribute 'id'

Python - Selenium Web Driver error - self._driver.execute - AttributeError: 'unicode' object has no attribute 'id'

我在这里找到了答案,但我的代码已经执行了建议的操作,但仍然产生相同的错误,所以我希望得到另一个答案。

这是我调用 ActionChains 的代码:

    elif first_col_value == first_col_in_assign:
        res2, assign_string = assign_cmd(spreadsheet_name, row)
        print "Got to main 8 - res2/cmd_string: %s %s" % (res2, assign_string)
        # assign_string2 = u"search_field = driver.find_element_by_name(“q”)"
        if not res2:
            exit(False)
        else:
            action = webdriver.ActionChains(driver).move_to_element(assign_string)
            action.perform()
            continue

这是从电子表格构建的 assign_string 的样子:

    In assign_cmd - param1 = %s search_field
    In assign_cmd - param2 = %s driver.find_element_by_name
    In assign_cmd - param3 = %s “q”
    In assign_cmd - param4 = %s #
    Got to main 8 - res2/assign_string: True search_field = driver.find_element_by_name(“q”)

这是错误:

    Traceback (most recent call last):
      File "/home/susan/PycharmProjects/justPython/test1.py", line 397, in <module>
      action.perform()
      File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/action_chains.py", line 70, in perform
action()
      File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/common/action_chains.py", line 215, in <lambda>
      self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
      AttributeError: 'unicode' object has no attribute 'id'

      Process finished with exit code 1

我尝试将 unicode 字符串直接放入我的代码中,即上面注释掉的行,但它产生了相同的错误。我被困住了,非常感谢您能给我的任何帮助。非常感谢。

move_to_element() 假定您传递的是之前找到的元素,而不是字符串:

move_to_element(to_element)

Moving the mouse to the middle of an element.

例如:

element = driver.find_element_by_id('myid')
action = webdriver.ActionChains(driver).move_to_element(element)
action.perform()

如果您可以控制传入的电子表格配置,我会稍微重新组织一下。我没有 find_element_by_* 字符串,而是每个元素都有两件事:一种定位器和一个定位器本身,例如:

|   type   |   value            |
|   xpath  |  //div[@id="test"] |
|   name   |  q                 |
...

然后,在您的测试中,您可以使用 find_element() method 来准确接收一种定位器和一个值:

 locator_type, locator_value = get_locator_from_spreadsheet(...)
 element = driver.find_element(locator_type, locator_value)

 action = webdriver.ActionChains(driver).move_to_element(element)
 action.perform()