首页 > 解决方案 > 使用 python selenium webdriver 从提示警报中获取文本

问题描述

我正在尝试抓取此页面:https ://foundation.app/@bryanmarktaylor 。我遇到的问题是如何获取头像下方复制到剪贴板按钮左侧的数字(0x068C ...)。当我在 Chrome 中使用 python selenium webdriver 时,浏览器没有将数字复制到剪贴板,而是显示提示警报,显示复制到剪贴板:Ctrl+C,Enter并显示一个包含我需要的数字的文本框。

我无法检查警报代码以捕获该元素。我试过使用

alert = driver.switch_to.alert
alert.send_keys(Keys.CONTROL, 'c')

但它给了我

TypeError: send_keys() takes 2 positional arguments but 3 were given

我也尝试过使用 JS 脚本

driver.execute_script("""arguments[0].getAttribute("value");""", alert)

但看起来我无法将警报元素作为参数发送

TypeError: Object of type Alert is not JSON serializable

标签: javascriptpythonseleniumweb-scraping

解决方案


您可以重新定义警报以保存消息:

driver.execute_script('window.alert = text => window.alertText = text')
// do something that triggers the alert
alert_text = driver.execute_script('return window.alertText')

推荐阅读