运行抓取工具时,我正在编写过程中,我需要与用户交互,但不喜欢通过控制台,因为这意味着在控制台和浏览器之间切换。
问题是我不知道如何获得结果,例如:
r = self.driver.execute_script('return confirm("test press ok or cancel");')
当我按“确定”或“取消”时,不会产生任何结果。我首先必须等到警报弹出,然后再次等待,直到我得到
NoAlertPresentException
使用常用的 try/ except 和
alert = self.driver.switch_to.alert
并继续,直到我按下
NoAlertPresentException
。现在的问题是做alert = ....
核攻击吗
r = self.driver.execute_script
如果是这种情况,我如何获取 python selenium 脚本创建警报的值,这是否可能?
我遇到了完全相同的问题。在 JavaScript 中,
confirm()
是一个阻塞函数。其他代码等待它返回。然而,Selenium 以某种方式规避了这一点,这意味着弹出窗口会立即关闭并返回 None
。
driver.execute_script("return confirm('Do you like apples?');")
这对于所有三个弹出窗口都是如此。 (列出的值是它们应该返回的值)。
alert()
返回None
confirm()
返回bool
prompt()
返回str
让它们正确返回的方法是将它们的值分配给一个预先存在的变量。
driver.execute_script("let response;")
driver.execute_script("response = confirm('Do you like apples?');")
user_likes_apples = driver.execute_script("return response;")
仅当您在完全单独的调用中定义
response
时,这才有效。如果您不调用这三个函数之一,则无论 Selenium 使用什么过滤器,都不适用。以下不起作用。
driver.execute_script("let response; response = confirm('Do you like apples?');")
driver.execute_script("return response;")
正如我所说,Selenium 会以某种方式在这些弹出窗口打开后立即将其关闭,至少就我而言是这样。我不知道这是否是我可以提供给司机的一个选项;我试过了。尽管如此,我在下面开发了一个示例,A) 阻止弹出窗口立即关闭,B) 捕获它们的返回值。
希望这有用。
from typing import Optional
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException, NoSuchWindowException, NoAlertPresentException
class PopupDriver(webdriver.Chrome):
# Show a popup in the browser
def _show_popup(self, popup: str, message: str) -> Optional[object]:
self.execute_script("let result;") # must be seperate
self.execute_script("result = %s('%s');" % (popup, message))
self.wait.until(EC.alert_is_present())
# Function to determine whether user has closed alert
def popup_is_closed(driver: webdriver.Chrome) -> bool:
try: response = dir(self.switch_to.alert)
except NoAlertPresentException: return True
return False
# Wait until alert is closed by user
self.wait.until(popup_is_closed)
# Return alert text value
return self.execute_script("return result;")
# Show an alert popup in the browser
def show_alert(self, message: str) -> None:
self._show_popup("alert", message)
# Show a confirmation popup in the browser
def show_confirmation(self, message: str) -> bool:
return self._show_popup("confirm", message)
# Show a prompt popup in the browser
def show_prompt(self, message: str) -> str:
return self._show_popup("prompt", message)
# Oh so difficult
def ask_the_hard_questions(self) -> None:
self.show_alert("Hello world!")
user_is_sane = self.show_confirmation("Continue if you think the world is a sphere.")
print("You think that the Earth is ", "not " * user_is_sane, "flat.", sep="")
print("Your name is", self.show_prompt(r"What\'s your name?")) # escape single quote
# Handle exceptions
def run(self) -> None:
try: self.ask_the_hard_questions()
except TimeoutException: # user did not respond within timeout
try: self.show_alert("You timed out. Stumped, huh?")
except TimeoutException: pass
except NoSuchWindowException: pass # user closed the window
finally: self.quit()
if __name__ == "__main__":
p = PopupDriver()
p.run()