【问题标题】:Perform TAB action until active element is the required element - Python执行 TAB 操作,直到活动元素是所需元素 - Python
【发布时间】:2018-11-11 05:43:30
【问题描述】:

我想执行 TAB 操作,直到到达特定的 Web 元素。在活动元素是下面提到的元素之前,必须执行 TAB 操作。

>name = driver.find_element_by_name("name")
>name.send_keys("ABC")
>group = driver.find_element_by_name("group") 
>group.send_keys("DEF")

我能够找到元素直到上述状态。之后,我想执行 TAB 操作,直到找到下面提到的元素。我想使用循环会有所帮助。

elem = driver.find_element_by_css_selector('.PeriodCell input')

请在下面找到 HTML 代码

<div class="PeriodCell" style="left:px; width:112px;">
<div class="Effort forecasting">
<div class="entity field-value-copy-selected">
<input type="text" value="0.0" data-start="2014-09-20">
</div>
</div>
<div class="Effort unmet zero" title="">0.0
</div>
</div>

请帮忙。提前致谢。

【问题讨论】:

  • 为什么你需要一个 tab 动作来点击那个元素?
  • 标签操作from pywinauto.keyboard import SendKeysSendKeys("TAB ,number of the tab")
  • 我执行选项卡操作以从该元素移动到下一个元素。我想继续这样做,直到达到以下元素 > elem = driver.find_element_by_css_selector('.PeriodCell input')
  • 你可以直接转到该元素而无需选项卡操作
  • 我试过了。那个地方有一个水平滚动条,默认情况下滚动条向右移动一点。所以元素是隐藏的。我收到以下错误,ElementNotVisibleException: element not visible

标签: python selenium selenium-webdriver


【解决方案1】:

您可以使用以下方法之一将元素带到屏幕的可见部分。

  1. 使用driver.execute_script("arguments[0].scrollIntoView();", element) 你可以阅读更多关于scrollIntoView()方法here的信息。

  2. 使用 Selenium webdriver 的 Actions 类。

从 selenium.webdriver.common.action_chains 导入 ActionChains

element = driver.find_element_by_css_selector('.PeriodCell input')
actions = ActionChains(driver)
actions.move_to_element(element).perform()

你可以阅读这两种方法的区别here

如果您仍然需要使用 TAB 操作来到达元素

from selenium.webdriver.common.keys import Keys

并使用 .send_keys(Keys.TAB) 将 TAB 键发送到元素

【讨论】:

  • 我收到此错误 ElementNotVisibleException: element not visible
  • @Abraham :我的回答有 3 种方法。特别是哪种方法会给您这个错误?
【解决方案2】:

在找到特定的WebElement 之前执行TAB Action 将不符合最佳实践。根据您的评论元素被隐藏,因此您需要先将元素带入Viewport,然后调用click()/send_keys(),如下所示:

myElement = driver.find_element_by_xpath("//div[@class='PeriodCell']//input[@type='text'][@value=\"0.0\"]")
driver.execute_script("return arguments[0].scrollIntoView(true);", myElement)
# perfrom any action on the element

但是使用TAB Action 的替代方法如下:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

global element
element = driver.find_element_by_name("name")
element.send_keys("ABC")
element = driver.find_element_by_name("group") 
element.send_keys("DEF")
while True:
    element.send_keys(Keys.TAB)
    element = driver.switch_to_active_element()
    if (element.get_attribute("type")=='text' and element.get_attribute("value")=='0.0' and element.get_attribute("data-start")=='2014-09-20'):
    print("Element found")
    break
# do anythin with the element

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2020-07-24
    • 2022-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多