如何修复selenium调用以单击按钮(在python中)?

2024-04-19 00:12:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在selenium中单击一个WEB按钮,但这比听起来更复杂。下面是我使用的python代码(在单元测试中):

def search(self, key, value):
    """To return an element with the given key-value pair"""
    elements = self.driver.find_elements_by_xpath("//*[@%s]"%key)
    for element in elements:
        if element.get_attribute(key) == value:
            return element
    return None

def test1(self):
    self.driver = webdriver.Firefox()
    self.driver.implicitly_wait(20)
    self.driver.get("https://www.swisscom.ch/de/privatkunden.html")
    button = self.search("data-tracking-title", "Mobile_Handys & Tablets")
    element = self.driver.find_element_by_id("scs-pageheader-navigation-link-1")
    hover = ActionChains(self.driver).move_to_element(element)
    hover.perform()
    button.click()

    hrefs = self.driver.find_element_by_xpath("//div[@id='gridProduct10247118']")

出现错误时:

^{pr2}$

好吧,这个错误是有意义的,因为selenium似乎没有单击我在上面搜索的button-元素。在

为什么selenium不执行“点击”按钮?我错过了什么?在

有时它根本不起作用,在这种情况下,button就是{}。然后,你需要重复整个测试不变,也许它会起作用。怎么解决?我试着增加等待时间,但也没用。。。在


Tags: keyselfsearchbyreturnvaluedefdriver
1条回答
网友
1楼 · 发布于 2024-04-19 00:12:52

答案是重新排列一些代码行!正确的顺序是:

element = self.driver.find_element_by_id("scs-pageheader-navigation-link-1")
hover = ActionChains(self.driver).move_to_element(element)#.click(self.search("data-tracking-title", "Mobile_Handys & Tablets")).perform()
hover.perform()
button = self.search("data-tracking-title", "Mobile_Handys & Tablets")
button.click()

我可能的解释是:首先,必须执行“悬停”操作,然后找到要单击的按钮。看起来原始按钮的“hidden”属性在“hover”操作后仍然设置。。。在

相关问题 更多 >