python-3.x - 程序没有完成任务就结束了
问题描述
while
当我运行我的脚本时,它会在完成循环中的任务之前结束。
driver = webdriver.Chrome()
driver.get('http://example.com')
#input("Press any key to continue1")
s_b_c_status = "False"
while s_b_c_status == "True":
try:
if(driver.find_element_by_xpath("//div[@role='button' and @title='Status']")):
s_b_c_status = "True"
except NoSuchElementException:
s_b_c_status = "False"
if(s_b_c_status == "True"):
print("Scanning Done!")
else:
print("Error")
由于我的网站没有它应该始终打印的元素Error
,但是当我运行我的代码时它只打印Error
一次(尽管它是在while
循环中检查的)。
我到底需要什么: 脚本应该检查元素是否存在,直到元素存在,然后运行其余代码。
解决方案
您的代码在逻辑上有明显缺陷:
s_b_c_status = "False"
while s_b_c_status == "True"
您已定义s_b_c_status
为"False"
,因此您的while
循环甚至不会进行一次迭代...
如果您需要等待元素出现在 DOM 中,请尝试实现ExplicitWait:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.Chrome()
driver.get('http://example.com')
try:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@role='button' and @title='Status']")))
except TimeoutException:
print("Element not found")
推荐阅读
- html - CSS:悬停选择器不适用于按钮
- docker - 用于 mysql、phpmyadmin 和 nginx 的 Docker-compose
- git - 本地分支中删除的 Git 恢复文件
- javascript - 如何从 A-Frame 上的 GLB 3D 对象获取动画剪辑的名称?
- dynamics-crm - Dynamics 2016 Web API C# 创建产品
- python - pylint 对已安装库的所有导入标记错误
- eclipse - javafx调试时如何观察serpinski三角形是如何绘制的?
- mysql - 在mysql中添加一个指示行号的新列
- swiftui - 为什么我的 TextField 的背景没有变成我设置的颜色?
- python - Python文件读取未获取所有字符