我刚开始使用 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 秒运行一次该代码,您需要做两件事:
您需要创建 30 秒的延迟。最简单的方法是使用
time
模块来创建延迟。例如:import time # some code time.sleep(30) # delays for 30 seconds
您需要重复该操作。最简单的方法是使用 while 循环来检查条件。例如:
keep_running = True while(keep_running): # your repeatable code
这样,您稍后可以在 while 循环内的代码中设置一些逻辑,这些逻辑可能会将
keep_running
变量设置为 False,从而结束循环(例如,一旦找到您的文本)正在寻找 1000 次,或者按下按钮等)。
关于Python Selenium 不断检查页面源代码中的短语,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35529637/