【问题标题】:selenium webdriver actionchains not working as expectedselenium webdriver actionchains 没有按预期工作
【发布时间】:2020-04-07 03:33:24
【问题描述】:

我在 selenium webdriver 中使用动作链下拉,这是我的代码,谁能帮我找出问题所在。这次我没有使用页面对象模式,所以这里没有“self”参数。

from selenium import webdriver
from behave import given, when, then
from selenium.webdriver.common.by import By
from selenium.webdriver import ActionChains


@given('Open RF page')
def open_website(context):
    context.driver.get('https://www.raymourflanigan.com/')


@when('Select Living Room')
def select_living_room(context):
    driver = webdriver.Chrome()
    actions = ActionChains(driver)
    menu = context.driver.find_element(By.XPATH, "//*[@id='Container']/div[1]/div[3]/div[1]/a")
    sofa = context.driver.find_element(By.XPATH, "//*[@id='Container']/div[1]/div[3]/div[1]/div/div[1]/ul/li[2]/a")
    actions.move_to_element(menu).move_to_element(sofa).click()


@then("Verify {product} are available")
def verify(context, product):
    result = context.driver.find_element(By.CSS_SELECTOR, "h1.Category_Bnr_Title").text
    assert 'Sofas & Couches' in result,  f"Expected text is:  {result}."

另外,我删除了perform(),因为由于某种原因,第二个函数不能在其中使用perform()。似乎没有它也无法正常工作,所以如果有人知道为什么并且可以帮助我,那就太好了!我只是学习)提前谢谢你!

【问题讨论】:

    标签: python selenium selenium-webdriver automation


    【解决方案1】:

    有一些问题,但没什么大不了的。似乎所有更改都需要在select_living_room 中完成。

    • select_living_room 在它的参数中使用了一个context 对象,但它首先要做的是创建一个全新的webDriver。但是然后它访问了一个完全不同的webDriver,它是context 的成员。我猜您正在尝试执行以下操作之一:
      1. 接受context,其中已包含驱动程序。如果是这种情况,请摆脱这个:driver = webdriver.Chrome()
      2. 创建一个 new 驱动程序作为context 的属性。在这种情况下,更改为:context.driver = webdriver.Chrome()
    • 在任何一种情况下,我都看不到在驱动程序上调用get 以打开页面的任何地方。在select_living_room 需要拨打open_website
    • ActionChain 未运行。最后需要添加perform() 调用。

    我将select_living_room 更改为这样工作(假设webDriver 已经在context 内部设置):

    @when('Select Living Room')
    def select_living_room(context):
        open_website(context)
        menu = context.driver.find_element(By.XPATH, "//*[@id='Container']/div[1]/div[3]/div[1]/a")
        sofa = context.driver.find_element(By.XPATH, "//*[@id='Container']/div[1]/div[3]/div[1]/div/div[1]/ul/li[2]/a")
        actions = ActionChains(context.driver)
        actions.move_to_element(menu).move_to_element(sofa).click().perform()
    

    然后像这样运行:

    opts = webdriver.ChromeOptions()
    ctx = Context(webdriver.Chrome('path/to/chromedriver', options=opts))
    select_living_room(ctx)
    verify(ctx, None)
    

    请注意,您没有提及 Context 是什么。我把它删掉了:

    class Context:
      def __init__(self, ctx):
        self.driver = ctx
    

    【讨论】:

      猜你喜欢
      • 2017-12-13
      • 2016-11-29
      • 2013-11-24
      • 1970-01-01
      • 2012-08-15
      • 1970-01-01
      • 2021-10-19
      • 2020-03-18
      • 2012-06-14
      相关资源
      最近更新 更多