Python Selenium 不断检查页面源代码中的短语

标签 python selenium selenium-webdriver

我刚开始使用 Python。我正在尝试使用 Selenium 编写一个脚本,该脚本打开 Firefox 浏览器并检查页面源代码中是否存在特定短语。

到目前为止我有这个...

from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.example.com/')
current_page_source = driver.page_source
print(current_page_source)

if "my phrase" in current_page_source :
    print ("Phrase Is Present")
else:
    print ("Phrase Is Not Present")

这工作得很好,但我希望它能够每 30 秒持续检查一次源。

我需要使用 for 循环来实现此目的吗?

最佳答案

为了每 30 秒运行一次该代码,您需要做两件事:

  1. 您需要创建 30 秒的延迟。最简单的方法是使用 time 模块来创建延迟。例如:

    import time
    # some code
    time.sleep(30) # delays for 30 seconds
    
  2. 您需要重复该操作。最简单的方法是使用 while 循环来检查条件。例如:

    keep_running = True
    
    while(keep_running):
        # your repeatable code
    

    这样,您稍后可以在 while 循环内的代码中设置一些逻辑,这些逻辑可能会将 keep_running 变量设置为 False,从而结束循环(例如,一旦找到您的文本)正在寻找 1000 次,或者按下按钮等)。

关于Python Selenium 不断检查页面源代码中的短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529637/

相关文章:

python - tensorflow 2.0 : tf. GradientTape().gradient() 返回无

c# - 等待时发生 StaleElementReferenceException

java - 当我在步骤 def 方法中使用 Cucumber(场景场景)参数时,显示使用 1 个参数声明的错误。小 cucumber 步骤有 0 个参数

python - 切换到 selenium webdriver 中的 web 对话框 : Python

Java Selenium 错误 : NoClassDefFoundError: org/openqa/selenium/HasAuthentication

XPath 中带有字符串变量的 Java XPath 语法

java - 创建 ECDSA DER 编码签名

python - 当大小超过 1 MB 时按顺序创建新文件

python - 如何使用 Authlib 和 Gspread 刷新身份验证 token ?

ajax - 如何在 selenium 中检测是否通过 ajax 加载了 javascript 文件?