【问题标题】:How to Get Int from JS Prompt Using Selenium in Python如何在 Python 中使用 Selenium 从 JS 提示中获取 Int
【发布时间】:2019-11-03 20:45:14
【问题描述】:

我正在尝试在 python 中使用 selenium 时在网页上为用户创建一个数字提示。

这是我写的代码,但它返回None

driver = webdriver.Chrome()
driver.get('https://www.google.com')

input_number = driver.execute_script('return parseInt(prompt("Enter a number", 20));')

print(input_number)

【问题讨论】:

  • alert/confirm/prompt 在 Chrome 的 executeStript 中不起作用。也许是 Firefox。
  • @pguardiario 在下面查看我的答案

标签: javascript python selenium selenium-chromedriver


【解决方案1】:

所以我想出了问题的答案。

以下是可能遇到相同问题的任何人的代码:

from selenium.common.exceptions import UnexpectedAlertPresentException

driver = webdriver.Chrome()
driver.get('https://www.google.com')

while True:
    try:
        driver.execute_script("var a = prompt('Enter a number');document.body.setAttribute('user-manual-input', a)")
        sleep(10)  # must 
        print(driver.find_element_by_tag_name('body').get_attribute('user-manual-input')) # get the text
        break

     except (UnexpectedAlertPresentException):
        pass

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2020-09-24
    • 2020-12-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-07
    • 2020-11-05
    相关资源
    最近更新 更多