Python 中的动态变量 while 循环



我在循环代码时得到了这个python硒。

  1. 如果实际点小于或等于 9,则执行任务 A
  2. 否则,如果实际点大于 9,则执行任务 B
  3. 执行 While 循环,直到实际点大于 9

这是我的代码

strpoints = driver.find_element_by_class_name("fs18").text
points = slice(13, len(strpoints)-20)
actualpoints = strpoints[points]
d = 0

while (d + actualpoints <9):
# TASK A!!!
print(actualpoints + ' Points! Skipping.')
time.sleep(2)
driver.find_element_by_class_name('skip_button_single').click()
time.sleep(8)
if (d >= 10):
break
# TASK B!!!
print(actualpoints + ' Points! Go for it!')

问题:

上面的代码无法正常工作,因为变量actualpoints是动态的。

如果实际值<9,它将执行分配的任务 B,但不幸的是,它返回相同的变量并且永远不会更改。

任务 A,重新加载页面并显示应存储在名为actualpoints的变量中的新数字。

与我的代码和变量相关的其他详细信息:

  • strpoints = 获取包含数字的字符串。此字符串的一部分是静态文本和动态(数字)。示例:以下您将获得 12 分。
  • 点=切片strpoints
  • 实际点数 = 切片后的结果strpoints.动态值。
  • 将执行循环,直到 10>

知道代码有什么问题吗?

我不确定这是否会解决问题,但也许您可以添加一个实际点验证方法和变量来保存最后一个实际点值?

这是您的代码和我所做的一些补充。 如果我正确阅读了任务 A,我会将您的初始过程重新设计到 while 循环中,但请随时修改它以满足您的需求。

strpoints = driver.find_element_by_class_name("fs18").text
points = slice(13, len(strpoints)-20)
actualpoints = strpoints[points]
"""
Create a temporary variable equal to the initial actualpoints value
"""
old_actualpoints = actualpoints
d = 0
def validate_actualpoints():
"""
Simple value check query. Returns actual actualpoints value.
"""
if old_actualpoints != actualpoints:
old_actualpoints = actualpoints
return actualpoints

while old_actualpoints == actualpoints:
while (d + actualpoints < 9):
# TASK A!!!
print(actualpoints + ' Points! Skipping.')
time.sleep(2)
driver.find_element_by_class_name('skip_button_single').click()
""" Move the initial process into the while loop and re-run based on TASK A """
strpoints = driver.find_element_by_class_name("fs18").text
points = slice(13, len(strpoints)-20)
actualpoints = strpoints[points]
time.sleep(8)
if (d >= 10):
break
"""
Update our temporary variable here?
(Possibly not needed.)
"""
old_actualpoints = validate_actualpoints()
break
# TASK B!!!
print(actualpoints + ' Points! Go for it!')

在下面的代码中,time.sleep替换为waitwhile替换为for循环。每次迭代都strpoints使用更新的值。用于从strpoints中提取points数的正则表达式。

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import re
#...
wait = WebDriverWait(driver, 10)
for i in range(10):
str_points = wait.until(EC.visibility_of_element_located((By.CLASS_NAME, "fs18"))).text
print("str_points: " + str_points)
points = re.search("\d+", str_points)[0]
if int(points) > 9:
break
wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "skip_button_single"))).click()
//time.sleep(8)
print(f'{points} Points! Go for it!')

最新更新