【问题标题】:Can't click a button with javascript using execute_script Selenium无法使用execute_script Selenium单击带有javascript的按钮
【发布时间】:2019-09-04 00:03:13
【问题描述】:

我正在尝试通过接受 cookie 并单击确认来摆脱 cookie 弹出窗口。单击输入“zgadzam się na”没有任何问题,但单击按钮“potwierdź”似乎是不可能的。我的代码:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

auction_url='https://www.g2a.com/grand-theft-auto-v-rockstar-key-global-i10000000788017'

driver = webdriver.Chrome()


driver.get(auction_url)

add_popup = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, '//*[@id="webklipper-publisher-widget-container-notification-frame"]'))
)

driver.switch_to.frame(driver.find_element_by_xpath('//*[@id="webklipper- 
publisher-widget-container-notification-frame"]'))
print('ads popup detected')
time.sleep(1)
driver.find_element_by_xpath('//*[@id="webklipper-publisher-widget- 
container-notification-close-div"]').click()
print('ads popup closed')
driver.switch_to.default_content()

driver.execute_script("document.querySelector('#cookies-select-all').click();")#works fine
time.sleep(3)
driver.execute_script("document.querySelector('body > div:nth-child(76) > div > div > div > div > div.modal-options__buttons > button.btn.btn-primary').click();")#error

我得到的错误:

selenium.common.exceptions.WebDriverException: Message: javascript error: Cannot read property 'click' of null

有趣的是,当我在浏览器控制台中执行此 js 代码时,我没有收到任何错误

【问题讨论】:

标签: javascript python selenium selenium-webdriver automated-tests


【解决方案1】:

试试下面的代码,我可以正常工作:

driver.execute_script("document.querySelector('body > div:nth-child(60) > div > div > div > div > div.modal-options__buttons > button.btn.btn-primary > span').click();")

或者你可以使用下面的查找元素

driver.find_element_by_css_selector("div.modal-window button.btn-primary").click()

【讨论】:

    【解决方案2】:

    我发现这个网站创建了大量的<div class="ReactModalPortal"></div>,我使用的是 div:nth-child(x),其中 x 是这个奇怪的、非常量的空白 div。我的 x 是恒定的,所以我做出了错误的选择......

    这里有一个解决方案:

    driver.execute_script("document.getElementsByClassName('modal-options__buttons')[0].getElementsByTagName('button')[0].click()")
    

    【讨论】:

      【解决方案3】:

      代替

      driver.execute_script("document.querySelector('body > div:nth-child(76) > div > div > div > div > div.modal-options__buttons > button.btn.btn-primary').click();")#error
      

      尝试使用 CSS 选择器单击按钮。

      WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR,'button.btn.btn-primary span'))).click()
      

      【讨论】:

        猜你喜欢
        • 2019-10-20
        • 1970-01-01
        • 2015-09-26
        • 1970-01-01
        • 2021-08-13
        • 2019-05-30
        相关资源
        最近更新 更多